【发布时间】:2020-08-05 14:20:09
【问题描述】:
以下代码可以正常工作:
import threading
semaphore = threading.Semaphore(0)
def consumer():
semaphore.acquire()
print("consumer next")
def producer():
print("producer first")
semaphore.release()
if __name__ == '__main__':
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start()
t2.start()
以上代码反映了线程的生产者消费者问题。 打印结果为:
生产者优先
消费者下一个
所以我想使用进程信号量,但它不起作用
from multiprocessing import Process, Semaphore
s = Semaphore(0)
class producer(Process):
def __init__(self):
super().__init__()
def run(self):
global s
print("producer first")
s.release()
class consumer(Process):
def __init__(self):
super().__init__()
def run(self):
global s
s.acquire()
print("consumer next")
if __name__ == '__main__':
p1 = producer()
p2 = consumer()
p1.start()
p2.start()
“consumer next”没有显示,我写错了什么,为什么?
请问如何解决。
【问题讨论】: