2017-04-23 49 views
1

我定義如下兩個功能:的Python的Thread.join(時間)回不回

功能,使一個線程:

def join_group_thread(client, link): 
    thread_queue = queue.Queue() 
    thread_1 = threading.Thread(
     target=join_group, 
     name="Join Group Thread", 
     args=[client, link, thread_queue], 
    ) 
    thread_1.start() 
    thread_1.join(10) 
    return thread_queue.get() 

功能,在線程中運行:

def join_group(client, params, queue): 
    try: 
     response = client.invoke(ImportChatInviteRequest(params)) 
    except Exception as e: 
     response = str(e).replace("'","") 
    queue.put(response) 

main()我打電話join_group_thread這樣的:

result = join_group_thread(client, link) 

由於我在這裏設定時間爲10秒,因此我預計result = join_group_thread(client, link)最多需要10秒,但有時會永久掛起。

任何解釋?

回答

1

the docs

Queue.get(塊=真,超時=無)

卸下並從隊列中返回一個項目。如果可選args塊爲true並且超時時間爲無(默認值),則根據需要進行阻止,直到有 項目可用。

換句話說,在thread.join超時是沒有意義的,因爲隊列等待,直到結果是可用的。使用thread_queue.get(block=False)thread_queue.get_nowait()