Example with a queue:
Beside
Often it's easier to do this tasks with
import time from random import randint from queue import Queue from threading import Thread def fake_feed(): """ Generator function which yields endless values from 0 to 255. """ while True: time.sleep(1) yield randint(0, 255) def feed_consumer(feed_gen, queue): """ This function consumes the yielded values from feed_gen and put them into the queue. """ for value in feed_gen: queue.put(value) def worker(queue): """ Worker function, which just print the objects from queue. """ while value := queue.get(): print(value) print("Creating queue") queue = Queue() print("Calling fake_feed") feed_gen = fake_feed() print("Creating consumer_thread") consumer_thread = Thread(target=feed_consumer, args=(feed_gen, queue)) print("Creating worker_thread") worker_thread = Thread(target=worker, args=(queue,)) print("Starting both threads") consumer_thread.start() worker_thread.start()But it depends on your code and a
queue
is not the only thing, which can be used for synchronization.Beside
queue
, you could use Lock
, RLock
, Condition Objects, Semaphore, Event Objects, Timer Objects and Barrier Objects.Often it's easier to do this tasks with
asyncio
, if there is a good library and if you know asyncio
. Otherwise, should stick with the threading approach until you understand asyncio
.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!