简体   繁体   English

为什么我的python3的打印功能不是线程安全的?

[英]why my python3's print function is not thread safe?

Here is my code, but the output on screen is not what I expected.这是我的代码,但屏幕上的输出不是我所期望的。

import threading
import time
def foo_1():
    for i in range(10):
        print ("foo_1: ")
        time.sleep(0.2)
def foo_2():
    for i in range(10):
        print("foo_2: ")
        time.sleep(0.2)
t1=threading.Thread(target=foo_1)
t2=threading.Thread(target=foo_2)
t1.start()
t2.start()

Here is output, clearly some print function didn't print '\\n' before sleep.这是输出,显然某些打印功能在睡眠前没有打印 '\\n' 。 I don't know why :(我不知道为什么:(

foo_1: 
foo_2: 
foo_2: foo_1: 

foo_1: foo_2: 

foo_1: foo_2: 

foo_2: 
foo_1: 
foo_2: 
foo_1: 
foo_2: 
foo_1: 
foo_2: 
foo_1: 
foo_2: 
foo_1: 
foo_2: 
foo_1: 

You can simply use a lock to make it thread safe您可以简单地使用锁来使其线程安全

import threading
import time

lock = threading.Lock()

def foo_1():
    for i in range(10):
        with lock: print ("foo_1: ")
        time.sleep(0.2)

def foo_2():
    for i in range(10):
        with lock: print("foo_2: ")
        time.sleep(0.2)
t1=threading.Thread(target=foo_1)
t2=threading.Thread(target=foo_2)
t1.start()
t2.start()

Or you can define your own thread-safe print function:或者您可以定义自己的线程安全打印函数:

import threading
import time

lock = threading.Lock() # thread safe print def sprint(*args, **kwargs): with lock: print(*args, **kwargs) def foo_1(): for i in range(10): sprint ("foo_1: ") time.sleep(0.2) def foo_2(): for i in range(10): sprint("foo_2: ")
        time.sleep(0.2)

t1=threading.Thread(target=foo_1)
t2=threading.Thread(target=foo_2)
t1.start()
t2.start()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM