multithreading - Need help on producer and consumer thread in python -
i wanted create consumer , producer thread in python simultaneously, producer thread append queue , consumer thread retrieves item stored in queue. , need start consumer thread along producer. consumer thread should wait till queue gets item. , should terminate when there no item in queue. new python, please on this.
requirements:
if there list of 10 numbers, producer thread should insert queue 1 item, , consumer thread should retrieve number. both thread should start simultaneously .
from queue import queue import threading import time class producer(threading.thread): def __init__(self, list_of_numbers): threading.thread.__init__(self) self.list_items = list_of_numbers def run(self): in self.list_items: queue.put(str(i)) class consumer(threading.thread): def __init__(self): threading.thread.__init__(self) def run(self): while queue.not_empty: queue_ret = queue.get() print("retrieved", queue_ret) queue = queue() producers = producer([10,20,5,4,3,2,1]) consumers = consumer() producers.start() consumers.start() producers.join() consumers.join()
just put special item once done:
_im_done = object() class producer(threading.thread): def run(self): '''feed consumer until done''' queue.put(_im_done) class consumer(threading.thread): def run(self): while true: queue_ret = queue.get() if queue_ret _im_done: break '''normal execution'''
if there multiple consumers, have put item before stop:
class consumer(threading.thread): def run(self): while true: queue_ret = queue.get() if queue_ret _im_done: queue.put(_im_done) break '''normal execution'''
Comments
Post a Comment