信号量 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运用的方法一样。
推荐阅读
-
C语言--getchar()的使用
-
HBase 系列(六)——HBase Java API 的基本使用
-
创建基于ASP.NET core 3.1 的RazorPagesMovie项目(一)-创建和使用默认的模板
-
FineReport的概念和使用讲解
-
flask与Flask-CORS的使用
-
使用NuGet将我们的ASP.NET Core类库打包并将程序包(类库)发布到NuGet平台上进行管理
-
Python爬虫使用selenium爬取qq群的成员信息(全自动实现自动登陆)
-
php foreach循环中使用引用的问题
-
vue-router的简单使用
-
倒计时cocos定时器schude使用的过程中 帧率浮动较大导致执行时机不准确的问题解决