簡體   English   中英

Python多線程-計划隊列

[英]Python Multithreading - Schedule Queue

我不知道為什么會有這樣的問題,基本上,我想讓一個隊列在名為“ Worker”的程序期間不斷運行,然后每10秒左右運行一次。.另一種方法稱為“處理”的數據進入並處理數據。 假設以下情況,每10秒捕獲一次數據。((0,1,2,3,..... n),然后“過程”函數接收該數據,處理數據,結束,然后“工作人員” ”重新開始工作,直到程序結束為止。

我有以下代碼:

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

有任何想法嗎?

這是使用線程的另一種方法:

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