gpt4 book ai didi

python - Python 上的信号量

转载 作者:太空狗 更新时间:2023-10-29 17:31:59 25 4
gpt4 key购买 nike

几周前我开始用 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()

关于python - Python 上的信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31508574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com