3

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?

Community
  • 1
  • 1
Iorek
  • 571
  • 1
  • 13
  • 31

1 Answers1

4

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.

Laszlowaty
  • 1,295
  • 2
  • 11
  • 19