Semaphores on Python

后端 未结 4 1096
无人共我
无人共我 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:05

    It is working fine, its just that its printing too fast for you to see . Try putting a time.sleep() in both functions (a small amount) to sleep the thread for that much amount of time, to actually be able to see both 1 as well as 2.

    Example -

    import threading
    import time
    sem = threading.Semaphore()
    
    def fun1():
        while True:
            sem.acquire()
            print(1)
            sem.release()
            time.sleep(0.25)
    
    def fun2():
        while True:
            sem.acquire()
            print(2)
            sem.release()
            time.sleep(0.25)
    
    t = threading.Thread(target = fun1)
    t.start()
    t2 = threading.Thread(target = fun2)
    t2.start()
    

提交回复
热议问题