December 2018
Beginner to intermediate
796 pages
19h 54m
English
For this example, we will be using a normal Queue, from the queue module:
# comm_queue.pyimport threadingfrom queue import QueueSENTINEL = object()def producer(q, n): a, b = 0, 1 while a <= n: q.put(a) a, b = b, a + b q.put(SENTINEL)def consumer(q): while True: num = q.get() q.task_done() if num is SENTINEL: break print(f'Got number {num}')q = Queue()cns = threading.Thread(target=consumer, args=(q, ))prd = threading.Thread(target=producer, args=(q, 35))cns.start()prd.start()q.join()
The logic is very basic. We have a producer function that generates Fibonacci numbers and puts them in a queue. When the next number is greater than a given n, the producer exits the while loop, and puts one last thing in the queue: a SENTINEL ...
Read now
Unlock full access