簡體   English   中英

為什么我的python3的打印功能不是線程安全的?

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

這是我的代碼,但屏幕上的輸出不是我所期望的。

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()

這是輸出,顯然某些打印功能在睡眠前沒有打印 '\\n' 。 我不知道為什么:(

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: 

您可以簡單地使用鎖來使其線程安全

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()

或者您可以定義自己的線程安全打印函數:

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