2014-12-24 145 views
0

我將運行在另一個工作線程的消費者,代碼如下:在生產者/消費者模式中,我如何殺死消費者線程?

def Consumer(self): 
     while True: 
      condition.acquire() 
      if not queue: 
       condition.wait() 
      json = queue.pop() 
      clients[0].write_message(json) 
      condition.notify() 
      condition.release() 


t = threading.Thread(target=self.Consumer); 
t.start() 

然而,我發現,我不能殺了這項工作線程,該線程將被等待()後,所有的時間工作...

我試圖從程序員發送一個單一的消費者每當完成程序工作,如果消費者收到單,工作線程應該退出(),有可能做到這一點?

+1

要小心,目前您沒有在線程中運行消費者任務,您需要刪除'()'。 'threading.Thread(target = self.Consumer)' – GP89

+0

http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python – GP89

+0

非常感謝! !我也只是想知道爲什麼消費者不在工作線程:) :) – liuzhidong

回答

1

我來通知消費者線程應該停止其工作標準方法是發送假消息,(我把它改寫,以使其可以運行):

import threading 
condition = threading.Condition() 
queue = [] 
class Client(): 
    def write_message(self,msg): 
     print(msg) 

clients=[Client()] 

jobdone=object() 

def Consumer(): 
    while True: 
     condition.acquire() 
     try: 
      if not queue: 
       condition.wait() 
      json = queue.pop() 
      if json is jobdone: 
       break; 
      clients[0].write_message(json) 
     finally: 
      condition.release() 

t = threading.Thread(target=Consumer); 
t.start() 
import time 
time.sleep(2) 
condition.acquire() 
queue.append(jobdone) 
condition.notify() 
condition.release() 

反正考慮使用queue.Queue是標準並使同步變得簡單。以下是我的示例:

import threading 
import queue 
import time 
queue = queue.Queue() 

class Client(): 
    def write_message(self,msg): 
     print(msg) 
clients=[Client()] 

jobdone=object() 
def Consumer(): 
    while True: 
     json = queue.get() 
     if json is jobdone: 
      break; 
     clients[0].write_message(json) 

t = threading.Thread(target=Consumer); 
t.start() 
queue.put("Hello") 
queue.put("Word") 
time.sleep(2) 
queue.put(jobdone) 

t.join() 
#You can use also q.join() 
print("Job Done") 
+0

我喜歡這個主意!只是一點...我們應該在休息之前釋放條件:) – liuzhidong

+0

@liuzhidong我會解決它。謝謝 –

+0

不幸的是,如果有多個消費者,這將不可靠工作... – socketpair