Python threading print overwriting itself [duplicate]

。_饼干妹妹 提交于 2020-01-30 10:57:07

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/49130540/python-threading-print-overwriting-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!