1

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. 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: 
lizhuoxuan
  • 11
  • 1

1 Answers1

0

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()
minglyu
  • 2,958
  • 2
  • 13
  • 32