我來通知消費者線程應該停止其工作標準方法是發送假消息,(我把它改寫,以使其可以運行):
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")
要小心,目前您沒有在線程中運行消費者任務,您需要刪除'()'。 'threading.Thread(target = self.Consumer)' – GP89
http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python – GP89
非常感謝! !我也只是想知道爲什麼消費者不在工作線程:) :) – liuzhidong