2013-09-29 42 views
0

我不知道为什么我会遇到这样的问题,基本上,我希望有一个队列在程序名为“Worker”的过程中不断运行,然后, 10秒左右。另一种称为“过程”的方法进入并处理数据。假设以下数据每10秒捕获一次(0,1,2,3,...... n),然后“处理”函数接收该数据,处理数据,结束处理,然后处理“工人“重新开始工作,完成他们的工作,直到项目结束。Python多线程 - 计划队列

我有以下代码:

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

问题是什么是什么呢? – RickyA

+0

@RickyA我需要创建一个允许“工作者”线程收集数据的程序,然后每10秒钟“处理”将处理数据。这是重复的,而“真实”..是否有意义? – Phorce

+0

是的,有道理,但是你现在的代码有什么问题? – RickyA

回答

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)