exitmutexes = [False] * 10
def counter(myId, count):
for i in range(count):
stdoutmutex.acquire()
print('[%s] => %s' % (myId, i))
stdoutmutex.release()
exitmutexes[myId] = True # signal main thread
for i in range(10):
thread.start_new_thread(counter, (i, 100))
while False in exitmutexes: pass
print('Main thread exiting.')
The output of this script is similar to the prior—10 threads counting to 100 in parallel
and synchronizing their prints along the way. In fact, both of the last two counting
thread scripts produce roughly the same output as the original thread_count.py, albeit
without stdout corruption and with larger counts and different random ordering of
output lines. The main difference is that the main thread exits immediately after (and
no sooner than!) the spawned child threads:
C:\...\PP4E\System\Threads> python thread-count-wait2.py
...more deleted...
[4] => 98
[6] => 98
[8] => 98
[5] => 98
[0] => 99
[7] => 98
[9] => 98
[1] => 99
[3] => 99
[2] => 99
[4] => 99
[6] => 99
[8] => 99
[5] => 99
[7] => 99
[9] => 99
Main thread exiting.
Coding alternatives: busy loops, arguments, and context managers
Notice how the main threads of both of the last two scripts fall into busy-wait loops at
the end, which might become significant performance drains in tight applications. If
so, simply add a time.sleep call in the wait loops to insert a pause between end tests
and to free up the CPU for other tasks: this call pauses the calling thread only (in this
case, the main one). You might also try experimenting with adding sleep calls to the
thread function to simulate real work.
Threads | 197