简体   繁体   English

Python多线程-计划队列

[英]Python Multithreading - Schedule Queue

I don't know why I'm having such a problem with this, basically, I want to have a Queue that is constantly running during the program called "Worker" this then works, however, every 10 seconds or so.. Another method called "Process" comes in and processes the data. 我不知道为什么会有这样的问题,基本上,我想让一个队列在名为“ Worker”的程序期间不断运行,然后每10秒左右运行一次。.另一种方法称为“处理”的数据进入并处理数据。 Let's assume the following, data is captured every 10 seconds.. (0, 1, 2, 3, ..... n) and then the "Proces" function receives this, processes the data, ends, and then the "Worker" goes back to work and does their job until the program has ended. 假设以下情况,每10秒捕获一次数据。((0,1,2,3,..... n),然后“过程”函数接收该数据,处理数据,结束,然后“工作人员” ”重新开始工作,直到程序结束为止。

I have the following code: 我有以下代码:

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()

In this example, it would look like the following: 在此示例中,它将类似于以下内容:

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

Any ideas? 有任何想法吗?

Here is an alternative way using threads: 这是使用线程的另一种方法:

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)

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

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