I have a Python program that spawns multiple producer threads and then has a loop that waits for a Queue
object to have something in it. It looks something like this
for t in threads:
t.start()
while len(threads):
if not queue.empty():
response = queue.get()
# handle response
queue.task_done()
else:
sleep(1)
threads = [t for t in threads if t.is_alive()]
There has to be a more elegant way to do this. I have looked into all of the synchronization objects the threading
module provides, but I don't see how any of them could be applied.
FYI, the code I have works for what I am trying to do. I am a strong believer in not fixing something that isn't broken, but I just feel like there is a better way to do this that a better programmer would have done in the first place.
You can use a
weakref
, to test, if the thread is still alive: