繁体   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