Popular recipes by Uri Sternfeld http://code.activestate.com/recipes/users/4174615/2010-08-09T16:24:38-07:00ActiveState Code RecipesSynchronizing worker threads using a common input source (Python) 2010-08-09T16:24:38-07:00Uri Sternfeldhttp://code.activestate.com/recipes/users/4174615/http://code.activestate.com/recipes/577350-synchronizing-worker-threads-using-a-common-input-/ <p style="color: grey"> Python recipe 577350 by <a href="/recipes/users/4174615/">Uri Sternfeld</a> (<a href="/recipes/tags/multithreading/">multithreading</a>, <a href="/recipes/tags/synchronization/">synchronization</a>). </p> <p>This class is used to synchronize worker threads that get their input from a common source that changes over time, and may even be empty on some occasions.</p> <p>The problem is that the threads are unaware of the existence of other threads, and have no way of knowing whether any new input will be inserted by other threads. Instead of using a separate 'control' thread, or having the threads exit needlessly each time the input source is empty, a WorkersLounge instance can be used to synchronize them.</p> <p>The commonest example is using a shared Queue.Queue object, where each thread may put additional jobs into it depending on its current job. When the queue is empty, the other threads 'rest' in the 'lounge'. When the last thread with a job is trying to 'rest', all the threads exit. When a thread puts new jobs into the queue, it should wake up any resting thread by calling the 'back_to_work' method.</p>