[Example 20-8][demo_executor_map.py] Race condition bug in display function
On my machine, threads switch between the two print() calls in the display
function, causing output from different calls to interleave. For example, I get
multiple timestamps on the same line or mixed output from different loiter()
calls.
[22:43:48] Script starting. [22:43:48] loiter(0): doing nothing for 0s... [22:43:48] [22:43:48] loiter(1): doing nothing for 1s...loiter(0): done. [22:43:48] loiter(2): doing nothing for 2s... [22:43:48][22:43:48] loiter(3): doing nothing for 3s... results: <generator object Executor.map.<locals>.result_iterator at 0x000001E48D7C3CD0>
I tried combining the output into a single print() call, but the issue still
appears because print() with multiple arguments performs multiple writes to
stdout.
The solution I found was to use a lock.
from threading import Lock lock = Lock() def display(*args): with lock: print(strftime('[%H:%M:%S]'), end=' ') print(*args)