信号量 Semaphore的使用

2023年1月19日08:25:17
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运用的方法一样。

  • 作者:SHAN_9W
  • 原文链接:https://blog.csdn.net/u014248032/article/details/82624289
    更新时间:2023年1月19日08:25:17 ,共 757 字。