2016-07-22 39 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