繁体   English   中英

如何使功能通过多处理运行进行通信

[英]How to make function run by multiprocessing communicate

当True循环在迭代时,我想发出一个信号来更新等待它的Child.process并使用诸如整数,字典或字符串之类的数据。 在PyQt中,可以使用PyQt.Signal对象来完成。 Qt信号对象可以设置为字符串,字典或列表。 使用signal.emit方法可以“发出”一个可能被另一个对象“捕获”的变量。 如何在不使用PyQt信号对象的情况下使功能process与孩子和/或父母互动?

import time, multiprocessing

def process():
    num = int()
    while True:
        print '...sleeping %s' % num
        time.sleep(1)
        num += 1
        if num > 10:
            break
    return time.time() 


class Child(object):
    def __init__(self):
        super(Child, self).__init__()

    def process(self):
        proc = multiprocessing.Process(target=process)
        proc.start()

class Parent(object):
    def __init__(self):
        super(Parent, self).__init__()
        child = Child()
        time_completed = child.process()
        print 'time_completed: %s' % time_completed



obj = Parent()

使用multiprocessing.Queue对象使process函数与child对象然后与parent对象进行通信:

import time, multiprocessing

def process(queue):
    num = int()
    while True:
        queue.put('...sleeping %s' % num)
        time.sleep(1)
        num += 1
        if num > 5:
            break
    queue.put('...time completed %s' % time.time() ) 
    time.sleep(0.1)

class Child(object):
    def __init__(self):
        super(Child, self).__init__()
        self.queue = multiprocessing.Queue()
        self.proc = multiprocessing.Process(target=process, args=(self.queue,))

    def process(self):
        self.proc.start()

class Parent(object):
    def __init__(self):
        super(Parent, self).__init__()
        children = [Child() for i in range(3)]

        for child in children:
            child.process()

        for child in children:
            if child.proc.is_alive():
                if not child.queue.empty():
                    print child.queue.get()

obj = Parent()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM