[英]How to make workers communicate in Python multiprocessing to find best solution to problem?
[英]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.