欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

信号量 Semaphore的使用

程序员文章站 2022-06-04 21:59:37
...
from threading import Semaphore,Thread
import time,random

sm = Semaphore(5)

def task(i):
    sm.acquire()#加锁
    print("%s is doing" % i)
    time.sleep(random.randint(1,3))
    print("\n%s is leaving" % i)
    sm.release()#解锁

if __name__ == "__main__":
    for i in range(20):
        p = Thread(target=task,args=(i,))
        p.start()

设置Semaphore 即允许同时运行的线程或者进程数,比如总共有十个线程要运行,Semaphore设置为5,则同时运行的为五个

结果:

0 is doing
1 is doing
2 is doing
3 is doing
4 is doing

1 is leaving
5 is doing

2 is leaving
6 is doing

3 is leaving
7 is doing

0 is leaving
8 is doing

5 is leaving
9 is doing

4 is leaving
10 is doing

6 is leaving
11 is doing

7 is leaving
12 is doing

9 is leaving
13 is doing

8 is leaving
14 is doing

13 is leaving
15 is doing

12 is leaving
10 is leaving
11 is leaving


16 is doing
17 is doing
18 is doing

14 is leaving
19 is doing

17 is leaving

15 is leaving

19 is leaving

16 is leaving
18 is leaving

可以看出,只有一个线程运行结束了才能让另一个运行。

线程和进程里的Semaphore运用的方法一样。

相关标签: Semaphore 信号量