简体   繁体   中英

python semaphore in process

The following code works fine:


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()

The above code reflects the producer consumer problem of threads. The result of printing is:

producer first

consumer next

So I want to use process semaphore,but it not works


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()

the "consumer next" not show,What did I write wrong,Why?

How to solve it,please.

I think the reason is that global variables are transparent to processes,So I'm passing in variables instead of using global variables,Problem solved!

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM