我正在尝试在python中使用信号量,但无法使其按我想要的方式工作。
我有以下代码:
import os
import threading
import time
sem = threading.Semaphore(0)
pid = os.fork()
if pid == 0:
print("Blocking...", )
sem.acquire()
print("Pass!")
elif pid:
time.sleep(2) # Here goes code instead of sleep
print("Releasing...")
sem.release()
print("Released")
我希望它能打印:
Blocking...
Releasing...
Released
Pass!
但是它从未打印出
Pass!
,即使我做了sem.acquire()
,信号量也卡在了sem.release()
上,我不知道为什么,我在做什么错?
最佳答案
试试这个:
import os
import threading
import time
sem = threading.Semaphore() # default value is 1
pid = os.fork()
if pid == 0:
print("Blocking...", )
sem.acquire()
print("Pass!")
elif pid:
time.sleep(2)
print("Releasing...")
sem.release()
print("Released")
“进入”信号量是其值(value)的下降。
要获得准确的消息顺序,可以使用如下所示的内容:
import os, sys
import threading
import time
sem = threading.Semaphore(1)
pid = os.fork()
if pid == 0:
print("Blocking...")
sem.acquire()
time.sleep(2)
print("Pass!")
elif pid:
time.sleep(1)
print("Releasing...")
sem.release()
print("Released")
但是正确的解决方案是避免硬编码的“定时”,而是与某些队列或事件进行通信。
关于python - 在Python中使用threading.Semaphore(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59180330/