Python的信号量不支持负初始值。那么,如何使一个线程等待其他8个线程完成某项操作呢?如果Semophore支持负的初始值,则可以将其设置为-8,并使每个线程将值递增1,直到我们获得0,从而解除阻塞正在等待的线程。
我可以在关键部分中手动增加全局计数器,然后使用条件变量,但是我想看看是否还有其他建议。
最佳答案
当然答案来晚了,但是对其他人来说可以派上用场。
如果要等待8个不同的线程执行某项操作,则只需等待8次。
您可以使用以下命令将信号量初始化为0s = threading.Semaphore(0)
接着
for _ in range(8):
s.acquire()
会做的工作。完整示例:
import threading
import time
NUM_THREADS = 4
s = threading.Semaphore(0)
def thread_function(i):
print("start of thread", i)
time.sleep(1)
s.release()
print("end of thread", i)
def main_thread():
print("start of main thread")
threads = [
threading.Thread(target=thread_function, args=(i, ))
for i
in range(NUM_THREADS)
]
[t.start() for t in threads]
[s.acquire() for _ in range(NUM_THREADS)]
print("end of main thread")
main_thread()
可能的输出:start of main thread
start of thread 0
start of thread 1
start of thread 2
start of thread 3
end of thread 0
end of thread 2
end of thread 1
end of thread 3
end of main thread
关于python - Python信号量: I Need Negative Initial Value,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38024886/