2016-02-19 77 views
0

我有一個腳本,遵循本示例相同的邏輯。 基本上我插入物品到一個全局隊列中,並用while循環產生線程,該循環從隊列中獲取,並且調用task_done。python線程與同步隊列

如果我的while循環檢查隊列不是空的,我可以讓線程加入,但我想嘗試併入一個標誌,我可以設置自己退出循環。當我嘗試這樣做時,永遠加入線程塊。

下面是這並不非工作樣本加入會話:

import threading 
import queue 

class Mythread(threading.Thread): 
    def __init__(self): 
     super().__init__() 
     self.signal = False 
    def run(self): 
     global queue 
     while not self.signal: 
      item = q.get() 
      print(item) 
      q.task_done() 
    def stop(self): 
     self.signal = True 

q = queue.Queue 
for i in range(5000): 
    q.put(i) 

threads = [] 
for i in range(2): 
    t = Mythread() 
    threads.append(t) 

for t in threads: 
    t.start() 
q.join() 

for t in threads: 
    print(t.signal) <---- False 
    t.stop()    
    print(t.signal) <---- True 
    t.join()   <---- Blocks forever 

下面是使用隊列空

import threading 
import queue 

class Mythread(threading.Thread): 
    def __init__(self): 
     super().__init__() 
    def run(self): 
     global queue 
     while not q.empty(): 
      item = q.get() 
      print(item) 
      q.task_done() 

q = queue.Queue 
for i in range(5000): 
    q.put(i) 

threads = [] 
for i in range(2): 
    t = Mythread() 
    threads.append(t) 

for t in threads: 
    t.start() 

q.join() 

for t in threads: 
    t.join()   <---- Works fine 
    print(t.is_alive()) <--- returns False 

任何想法的作品的人嗎?

+0

實例教程:HTTP://inventwithpython.com/blog/2013/04/22/multithreaded-python-tutorial-with-threadworms/ –

+0

線程池是另一種可能的解決方案。您目前的代碼似乎是對同一邏輯的粗略重新實現。 –

回答

-1

q.get塊,這樣就不會達到你的病情時

+0

因爲q.get塊,這意味着我應該能夠安全地使用while循環檢查隊列是否爲空,或者我可以切換爲True,而只需在q join之後將其置於隊列中以跳出循環? – hashi