我不知道为什么我遇到这样的问题,基本上,我想要一个在名为“Worker”的程序中不断运行的队列,然后每10秒钟左右工作一次。另一种称为“进程”的方法进入并处理数据。让我们假设以下情况,每10秒捕获一次数据..(0,1,2,3,..... n)然后“Proces”函数接收到这个,处理数据,结束,然后“工人” “重新开始工作并完成工作,直到计划结束。
我有以下代码:
import multiprocessing as mp
import time
DELAY_SIZE = 10
def Worker(q):
print "I'm working..."
def Process(q):
print "I'm processing.."
queue = mp.Queue(maxsize=DELAY_SIZE)
p = mp.Process(target=Worker, args=(queue,))
p.start()
while True:
d = queue.get()
time.sleep(10)
Process()
在此示例中,它看起来如下所示:
I'm working...
I'm working...
I'm working...
...
...
...
I'm working...
I'm processing...
I'm processing...
I'm processing...
...
...
I'm working..
I'm working..
有什么想法吗?
答案 0 :(得分:1)
以下是使用线程的另一种方法:
import threading
import Queue
import time
class Worker(threading.Thread):
def __init__(self, q):
threading.Thread.__init__(self)
self._q = q
def run(self):
# here, worker does its job
# results are pushed to the shared queue
while True:
print 'I am working'
time.sleep(1)
result = time.time() # just an example
self._q.put(result)
def process(q):
while True:
if q.empty():
time.sleep(10)
print 'I am processing'
worker_result = q.get()
# do whatever you want with the result...
print " ", worker_result
if __name__ == '__main__':
shared_queue = Queue.Queue()
worker = Worker(shared_queue)
worker.start()
process(shared_queue)