Semaphores on Python

后端 未结 4 1079
无人共我
无人共我 2020-12-29 22:24

I\'ve started programming in Python a few weeks ago and was trying to use Semaphores to synchronize two simple threads, for learning purposes. Here is what I\'ve got:

<
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 23:10

    Also, you can use Lock/mutex method as following:

    import threading
    import time
    
    mutex = threading.Lock()  # is equal to threading.Semaphore(1)
    
    def fun1():
        while True:
            mutex.acquire()
            print(1)
            mutex.release()
            time.sleep(.5)
    
    def fun2():
        while True:
            mutex.acquire()
            print(2)
            mutex.release()
            time.sleep(.5)
    
    t1 = threading.Thread(target=fun1).start()
    t2 = threading.Thread(target=fun2).start()
    

    Another/Simpler style usage through "with":

    import threading
    import time
    
    mutex = threading.Lock()  # is equal to threading.Semaphore(1)
    
    def fun1():
        while True:
            with mutex:
                print(1)
            time.sleep(.5)
    
    def fun2():
        while True:
            with mutex:
                print(2)
            time.sleep(.5)
    
    t1 = threading.Thread(target=fun1).start()
    t2 = threading.Thread(target=fun2).start()
    

    [NOTE]:

    The difference between mutex, semaphore, and lock

提交回复
热议问题