Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python threading print overwriting itself [duplicate]

I have the following which threads a print function.

from threading import Thread
from random import *
import time

def PrintRandom():
    rand = random()
    time.sleep(rand)
    print(rand)

if __name__ == "__main__":
    Thread(target=PrintRandom).start()
    Thread(target=PrintRandom).start()

This works the majority of the time with the following being ouput

0.30041615558463897

0.5644155082254415

However, once in a blue moon, the following is output

0.56441550822544150.5644155082254416

The shell tries to print both at the same time and returns an incoherent statement. Is there anyway to ensure the first output?

like image 950
Iorek Avatar asked Aug 27 '26 05:08

Iorek


1 Answers

Yes - create queue. It can be list where you append new strings to be printed, and use seperate thread to remove first element from that list and print it. Make sure your printing thread runs in a while/for loop and uses sleep(0.1) method to not use too much CPU.

like image 151
Laszlowaty Avatar answered Aug 29 '26 03:08

Laszlowaty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!