【问题标题】:python semaphore in process进程中的python信号量
【发布时间】: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”没有显示,我写错了什么,为什么?

请问如何解决。

【问题讨论】:

    标签: python process semaphore


    【解决方案1】:

    我认为原因是全局变量对进程是透明的,所以我是传入变量而不是使用全局变量,问题解决了!

    from multiprocessing import Process, Semaphore
    class producer(Process):
        def __init__(self,s):
            super().__init__()
            self.s=s
        def run(self):
            print("producer first")
            self.s.release()
    
    class consumer(Process):
        def __init__(self,s):
            super().__init__()
            self.s=s
        def run(self):
            self.s.acquire()
            print("consumer next")
    
    if __name__ == '__main__':
        s = Semaphore(0)
        p2 = consumer(s)
        p2.start()
        #p2 start first ,but show result next
        p1 = producer(s)
        p1.start()
    

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 2015-05-25
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多