2016-07-22 17 views
0

在我的Python脚本中,我接收到一个持续的数据流,但想通过调用异步方法异步地推送数据。当方法可用时,存在于缓冲区中的数据总是被按下。Python - 通过线程管理异步方法

为了达到这个目的,我有一个不断被调用的try/catch函数,它创建一个执行方法的线程对象(当方法执行完成时我会返回),并且如果线程正在运行try/catch break 。

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 

会有更容易和更清洁的方式来写这个吗?

如果需要

回答

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(...)不会阻止主线程。

+0

我可以多次调用t = threading.Thread和t.start()吗?有时候可能没有数据,但我不希望线程退出 – BDillan

+0

在我的代码中,推送器线程不会退出,除非您将None值置于队列中。因此,在程序准备退出之前,不要将None值放入队列中。当没有数据时,推送器线程会阻止“get”调用。 – ErikR