Created
April 15, 2018 02:49
-
-
Save okakaino/40d2e3b50dac86836fa09ee7754fa740 to your computer and use it in GitHub Desktop.
An example of using producer consumer model in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import time | |
from queue import Queue | |
from threading import Thread | |
def produce(queue): | |
nums = range(5) | |
while True: | |
num = random.choice(nums) | |
queue.put(num) | |
print('Produced:', num) | |
time.sleep(random.randint(0, 5)) | |
def consume(queue): | |
while True: | |
num = queue.get() | |
queue.task_done() | |
print('Consumed:', num) | |
time.sleep(random.randint(0, 5)) | |
def main(): | |
q = Queue(10) | |
producer = Thread(target=produce, args=(q,)) | |
producer.start() | |
consumer = Thread(target=consume, args=(q,)) | |
consumer.start() | |
producer.join() | |
consumer.join() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment