Skip to content

[Example 20-8][demo_executor_map.py] Race condition bug in display function #68

@Kristiyan-Ivanov

Description

@Kristiyan-Ivanov

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions