我正在嘗試學習在 python 中實作它的生產者-消費者模式。我可以讓它作業,但由于某種原因,消費者一直在聽佇列中的某些內容并且沒有結束腳本。
我知道這是預期的行為,因為生產者可以以消費者消費的不同速率不斷向佇列添加內容。但是,就我而言,我已經有一個要由佇列處理的串列,我可以保證將來不會添加其他專案。
這是完整的作業代碼:
from threading import Thread
import time
import random
from queue import Queue
queue = Queue(10)
class ProducerThread(Thread):
def __init__(self, nums):
super().__init__()
self.nums = nums
def run(self):
global queue
while self.nums:
num = self.nums.pop(0)
queue.put(num)
print("Produced", num)
time.sleep(1)
class ConsumerThread(Thread):
def __init__(self, id):
super().__init__()
self.id = id
def run(self):
global queue
while True:
num = queue.get()
##do something here
queue.task_done()
print(f"Consumed {num} in consumer {self.id}")
time.sleep(1)
p = ProducerThread(list(range(5)))
l1 = ConsumerThread(1)
l2 = ConsumerThread(2)
p.start()
l1.start()
l2.start()
p.join()
l1.join()
l2.join()
我可以在消費者中替換哪個條件,while True以便它理解腳本已經結束?
提前致謝。
uj5u.com熱心網友回復:
我的答案已按您的要求寫出來。
STOP_TOKEN = "STOP" # Anything that wouldn't normally be in your queue.
class ProducerThread(Thread):
...
def run(self):
global queue
while self.nums:
num = self.nums.pop(0)
queue.put(num)
print("Produced", num)
time.sleep(1)
queue.put(STOP_TOKEN)
class ConsumerThread(Thread):
...
def run(self):
global queue
while True:
num = queue.get()
if num == STOP_TOKEN:
break
##do something here
queue.task_done()
print(f"Consumed {num} in consumer {self.id}")
time.sleep(1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/382686.html
