几周前,我开始使用Python进行编程,并试图使用Semaphores来同步两个简单的线程,以达到学习目的。这是我所拥有的:

import threading
sem = threading.Semaphore()

def fun1():
    while True:
        sem.acquire()
        print(1)
        sem.release()

def fun2():
    while True:
        sem.acquire()
        print(2)
        sem.release()

t = threading.Thread(target = fun1)
t.start()
t2 = threading.Thread(target = fun2)
t2.start()
但是它只打印1。如何使打印品交错显示?

最佳答案

它工作正常,只是它的打印速度太快而您看不到。尝试将time.sleep()放入这两个函数中(少量)以使线程休眠那么长的时间,以便实际上能够同时看到1和2。

例子 -

import threading
import time
sem = threading.Semaphore()

def fun1():
    while True:
        sem.acquire()
        print(1)
        sem.release()
        time.sleep(0.25)

def fun2():
    while True:
        sem.acquire()
        print(2)
        sem.release()
        time.sleep(0.25)

t = threading.Thread(target = fun1)
t.start()
t2 = threading.Thread(target = fun2)
t2.start()

09-28 12:32