Python - 通过线程管理异步方法

时间:2016-07-22 03:34:48

标签: python multithreading python-multithreading

在我的Python脚本中,我收到一个恒定的数据流,但想通过调用异步方法异步推送数据。当方法可用时,始终按下存在于缓冲区中的数据。

为了实现这一点,我有一个不断被调用的try / catch,它创建一个执行方法的线程对象(我假设在方法完成执行时返回),并且线程正在运行try / catch中断。

import thread
import threading
thr = None
...    

try:
  if thr.is_alive():
    print "thread running"
  else: 
    thr.Thread(target=move_current_data, args=(data_buffer))
    thr.start() 
    data_buffer.clear()
except NameError: 
  print ""   
except AttributeError:
  print "      


def move_current_data(data_buffer):
...    
  return

有没有更简单,更清晰的方式来写这个?

如果需要,我可以提供更多信息

1 个答案:

答案 0 :(得分:0)

您应该使用队列。一个线程只需要监视队列并推出任何新数据。当新数据可用时,主线程只会添加到队列中。

示例:

import threading
import queue

def pusher(q):
  while True:
    item = q.get()
    if item is None:
      return         # exit thread
    ...push data...

def main():
  q = Queue.Queue()
  # start up the pusher thread
  t = threading.Thread(target = pusher, args=(q))
  t.start()

  # add items
  q.put(item1)
  ...
  q.put(item2)
  ...
  ...
  # tell pusher to shut down when queue is empty
  # and wait for pusher to complete
  q.put(None)
  t.join()

请注意q.put(...)不会阻止主线程。

相关问题