I made my own script in python with multithreading. The problem is my output is completely overprinted, and I need a clear output print. In the picture below you can see the first 15 lines are fine, but after that its not good anymore.
Asked
Active
Viewed 90 times
0
-
You can prevent it by redefining the `print()` function as shown near the end of the code in this [answer](https://stackoverflow.com/a/66286326/355230) of mine to another threading question. – martineau Nov 29 '21 at 20:09
-
1Does this answer your question? [Python - Threads are printing at the same time messing up the text output](https://stackoverflow.com/questions/26688424/python-threads-are-printing-at-the-same-time-messing-up-the-text-output) – Tsyvarev Nov 29 '21 at 23:11
1 Answers
0
Race conditions
You are most likely running into a race condition where the code is printing the first part of the line before the next part of the line.
Example race
Problem code
print(timestamp)
print(part of log)
print(rest of log)
Example result (with two threads)
T1: prints timestamp
T2: prints timestamp
T2: prints part of log
T1: prints part of log
T1: prints rest of log
T2: prints rest of log
Reason code fails
The prints can interleave, especially if you have a lot of threads running or it has an unexpected spike in data input.
Example code with fix
log_string=f"{timestamp}{part of log}{rest of log}"
print(log_string)
Fix reason
If the print call happens all at once, it won't interleave the writes.
See also

ListsOfArrays
- 442
- 6
- 14