学习笔记(29):Python网络编程&并发编程-信号量

立即学习:https://edu.csdn.net/course/play/24458/296446?utm_source=blogtoedu

信号量(了解):也是一把锁semaphore

1.

from threading import Thread,Semaphore,currentThread
import time

#定义信号量(3把锁)
sm = Semaphore(3)

def task():
   
    with sm:
        print('%s acquires the sm' % currentThread().getName())
        time.sleep(1)

if __name__ == '__main__':
    for i in range(10):
        t = Thread(target=task)
        t.start()

2.

sm.acquire()
print('%s acquires the sm'%currentThread().getName())
sm.release()

#等价于
with sm:
    print('%s acquires the sm'%currentThread().getName())

发布了49 篇原创文章 · 获赞 11 · 访问量 570

猜你喜欢

转载自blog.csdn.net/qq_45769063/article/details/105092026