python - 在Python中使用threading.Semaphore()

标签 python multithreading semaphore

我正在尝试在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/

相关文章:

c - 未找到信号量符号 (c)

ios - 为什么Xcode和Time Profiler报告更快的iOS设备会占用更高的CPU使用率?

android - 是否可以检测 Activity 是否暂停? (线程问题)

python - 找到所有可能的 N 长度字谜 - 快速替代

python - BeautifulSoup: 'lxml' 和 'html.parser' 以及 'html5lib' 解析器有什么区别?

Python 骰子结果计数

python - pygame - 如何在没有 time.sleep() 的情况下缓慢更新 HP 条

c# - 为什么我的多线程应用程序没有执行它应该执行的操作?

mutex - 测量 mutex 或 futex 延迟

python - 如何解决TypeError : 'str' does not support the buffer interface?