I built the following code while studying about threads and queues from the following website.
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()
I get the following output:
python3 a3_4.py
Outputting: 1
Outputting: 2
Outputting: 3
Outputting: 4
But the program doesn't stop on its own.
I tried inserting else: break
but that only gives me Outputting: 1
Am I missing something very basic here?
答案 0 :(得分:1)
I think, you are simulating producer-consumer problem. The problem is that your producer thread stops properly, but there's no termination clause for your consumer thread(main thread). So I think You need to add some termination clause for your consumer method op().
May be :
def op(self):
self.start()
while True:
time.sleep(self.waiting_time)
if not self.q.empty():
print("Outputting: ", self.q.get())
else:
break