zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

2023-09-11 14:21:45 时间

立即学习: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())