簡體   English   中英

python中的生產者-消費者算法

[英]Producer-Consumer algorithm in python

我在從以下網站研究線程和隊列時構建了以下代碼。

from __future__ import print_function
import queue
import threading
import time

class a3_4(threading.Thread):
    q = queue.Queue()
    def __init__(self, begin, end, waiting_time):
        self.begin = begin
        self.end = end
        self.waiting_time = waiting_time
        threading.Thread.__init__(self)

    def run(self):
        while True:
            if self.begin != self.end:
                self.q.put(self.begin)
                self.begin += 1
                time.sleep(5)
            else:
                break
    def op(self):
        self.start()
        while True:
            if not self.q.empty():
                print("Outputting: ", self.q.get())
            time.sleep(self.waiting_time)

if __name__ == '__main__':
    myThread = a3_4(1, 5, 1)
    myThread.op()

我得到以下輸出:

python3 a3_4.py 
Outputting:  1
Outputting:  2
Outputting:  3
Outputting:  4

但該程序不會自行停止。 我嘗試插入else: break但這只會給我Outputting: 1我在這里錯過了一些非常基本的東西嗎?

我認為,您正在模擬生產者-消費者問題。 問題是您的生產者線程正確停止,但您的消費者線程(主線程)沒有終止子句。 所以我認為你需要為你的消費者方法 op() 添加一些終止子句。

也許 :

def op(self):
        self.start()
        while True:
            time.sleep(self.waiting_time)
            if not self.q.empty():
                print("Outputting: ", self.q.get())
            else:
                break

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM