0

我不知道为什么我会遇到这样的问题,基本上,我想要一个在名为“Worker”的程序期间不断运行的队列,然后它会工作,但是,每 10 秒左右.. 另一种方法称为“处理”的进来并处理数据。假设如下,每 10 秒捕获一次数据.. (0, 1, 2, 3, ..... n) 然后“Proces”函数接收到这个数据,处理数据,结束,然后“Worker” “回去工作,做他们的工作,直到项目结束。

我有以下代码:

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..

有任何想法吗?

4

1 回答 1

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)
于 2013-09-29T22:56:36.123 回答