Skip to content

Instantly share code, notes, and snippets.

@okakaino
Created April 15, 2018 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okakaino/40d2e3b50dac86836fa09ee7754fa740 to your computer and use it in GitHub Desktop.
Save okakaino/40d2e3b50dac86836fa09ee7754fa740 to your computer and use it in GitHub Desktop.
An example of using producer consumer model in python
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