线程中的samaphore信号量及event事件

时间:2022-04-11 22:54:49
一、信号量

samaphore: 在程序中意思为同时允许几个线程运行,比如我们去水上乐园的滑梯玩时,有四个滑梯,每一个滑梯上当没有人在中间玩滑下去时才允许上人,四个滑梯1,2,3,4,同时最多四个人,当少有一个滑下去完成了。后面补上,就是后面的人必须等前面有人完成了才能补上去。
- 互斥锁 同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据。常用在数据库、连接池等地方

import threading,time

def run(n):
semaphore.acquire()
time.sleep(1)
print("run the thread: %s\n" %n)
semaphore.release() if __name__ == '__main__': num= 0
samaphore = threading.BoundedSamaphore(5) #最多允许5个线程同时运行
for i in range(20):
t = threading.Thread(target=run,args=(i,))
t.start() while threading.active_count() != 1:
pass #print threading.active_count()
else:
print('----all threads done---')
print(num)
二、事件

An event is a simple synchronization object;

the event represents an internal flag, and threads

can wait for the flag to be set, or set or clear the flag themselves.

event = threading.Event()

a client thread can wait for the flag to be set

event.wait()

a server thread can set or reset it

event.set()

event.clear()

If the flag is set, the wait method doesn’t do anything.

If the flag is cleared, wait will block until it becomes set again.

Any number of threads may wait for the same event.

通过Event来实现两个或多个线程间的交互,下面是一个红绿灯的例子,即起动一个线程做交通指挥灯,生成几个线程做车辆,车辆行驶按红灯停,绿灯行的规则。

import threading,time
import random
def light():
if not event.isSet():
event.set() #wait就不阻塞 #绿灯状态
count = 0
while True:
if count < 10:
print('\033[42;1m--green light on---\033[0m')
elif count <13:
print('\033[43;1m--yellow light on---\033[0m')
elif count <20:
if event.isSet():
event.clear()
print('\033[41;1m--red light on---\033[0m')
else:
count = 0
event.set() #打开绿灯
time.sleep(1)
count +=1
def car(n):
while 1:
time.sleep(random.randrange(10))
if event.isSet(): #绿灯
print("car [%s] is running.." % n)
else:
print("car [%s] is waiting for the red light.." %n)
if __name__ == '__main__':
event = threading.Event()
Light = threading.Thread(target=light)
Light.start()
for i in range(3):
t = threading.Thread(target=car,args=(i,))
t.start()

event = threading.Event() 申请一个事件实例。 event.set() 设置标记, event.isSet() 如果标记设置返回True, event.wait()检查标记是否设置,如果没设置阻塞程序,直到标记被设置, event.clear()清空标记

线程中的samaphore信号量及event事件的更多相关文章

  1. 并发编程(五)——GIL全局解释器锁、死锁现象与递归锁、信号量、Event事件、线程queue

    GIL.死锁现象与递归锁.信号量.Event事件.线程queue 一.GIL全局解释器锁 1.什么是全局解释器锁 GIL本质就是一把互斥锁,相当于执行权限,每个进程内都会存在一把GIL,同一进程内的多 ...

  2. TCP协议下的服务端并发,GIL全局解释器锁,死锁,信号量,event事件,线程q

    TCP协议下的服务端并发,GIL全局解释器锁,死锁,信号量,event事件,线程q 一.TCP协议下的服务端并发 ''' 将不同的功能尽量拆分成不同的函数,拆分出来的功能可以被多个地方使用 TCP服务 ...

  3. 1&period;gil全局解释器锁&comma; 2&period; 死锁与递归锁 3&period; 信号量 4&period; Event事件 5&period; 线程queue

    gil本质就是一把互斥锁,相当于执行权限,每个进程都会存在一把gil,同一进程内的多个线程必须抢到gil 之后才能使用cpython解释器来执行自己的代码,同一进程下的多线程不能并行,但可以实现并发 ...

  4. Python 36 死锁现象和递归锁、信号量、Event事件、线程queue

    一:死锁现象和递归锁 所谓死锁: 是指两个或两个以上的进程或线程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去.此时称系统处于死锁状态或系统产生了死锁,这些永远 ...

  5. GIL全局解释锁,死锁,信号量,event事件,线程queue,TCP服务端实现并发

    一.GIL全局解释锁 在Cpython解释器才有GIL的概念,不是python的特点 在Cpython解释器中,同一个进程下开启的多线程,同一时刻只能有一个线程执行,无法利用多核优势. 1.GIL介绍 ...

  6. Python之网路编程之死锁,递归锁,信号量,Event事件,线程Queue

    一.死锁现象与递归锁 进程也是有死锁的 所谓死锁: 是指两个或两个以上的进程或线程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用, 它们都将无法推进下去.此时称系统处于死锁状态或系统 ...

  7. 并发编程(五)--GIL、死锁现象与递归锁、信号量、Event事件、线程queue

    一.GIL全局解释器锁 1.什么是全局解释器锁 GIL本质就是一把互斥锁,相当于执行权限,每个进程内都会存在一把GIL,同一进程内的多个线程,必须抢到GIL之后才能使用Cpython解释器来执行自己的 ...

  8. 并发编程 - 线程 - 1&period;互斥锁&sol;2&period;GIL解释器锁&sol;3&period;死锁与递归锁&sol;4&period;信号量&sol;5&period;Event事件&sol;6&period;定时器

    1.互斥锁: 原理:将并行变成串行 精髓:局部串行,只针对共享数据修改 保护不同的数据就应该用不用的锁 from threading import Thread, Lock import time n ...

  9. python并发编程-多线程实现服务端并发-GIL全局解释器锁-验证python多线程是否有用-死锁-递归锁-信号量-Event事件-线程结合队列-03

    目录 结合多线程实现服务端并发(不用socketserver模块) 服务端代码 客户端代码 CIL全局解释器锁****** 可能被问到的两个判断 与普通互斥锁的区别 验证python的多线程是否有用需 ...

随机推荐

  1. 单节点下多个Tomcat服务器并存的端口号配置

    一个服务器节点同时安装多个tomcat服务器时,如果仅仅修改访问端口号则会提示端口冲突启动失败,还需要修改另外端口号解决,一共需要修改3处地方,修改如下: 编辑配置文件:server.xml 1.首先 ...

  2. Nltest

    查看登陆到的DC:

  3. Esper系列&lpar;十二&rpar;Variables and Constants

    功能:变量和常量的定义及应用. EPL配置创建 1   "); 3  // 创建 orderBean 事件类型变量 bean 4  epAdmin.createEPL("creat ...

  4. ASP&period;NET C&num; 有程序集加不了解决办法

    在项目中添加app.config 获取在 web.config 添加 <?xml version="1.0"?> <configuration> <s ...

  5. Python进阶之decorator装饰器

    decorator装饰器 .note-content {font-family: "Helvetica Neue",Arial,"Hiragino Sans GB&quo ...

  6. mysq Point类型 查询和插入操作:insert和select

    首先,创建一个表名为geometry2的表,然后增加一个名为gemo的point类型的字段. insert方法有4中,例如以下所看到的://============================== ...

  7. 7&period;25 RPN转换

    思想: 目的:将中缀表达式(即标准形式的表达式)转换为后缀式. 例子:a+b*c+(d*e+f)*g转换成abc*+de*f+g*+ 转换原则: 1.当读到一个操作数时,立即将它放到输出中.操作符则不 ...

  8. 【LeetCode】289&period; Game of Life

    题目: According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a ce ...

  9. dskinlite&lpar;uieasy mfc界面库&rpar;使用记录1&colon; schema验证xml

    市场上的MFC第三方库很多,最终选定dskinlite企业版,成熟度比较高,当然价格也略贵. 在2017年仍然使用MFC是有些另类,但特定场景很适用,也适合不愿转型的老程序员. 目前处于学习阶段,欢迎 ...

  10. 『Python CoolBook』使用ctypes访问C代码&lowbar;下&lowbar;demo进阶

    点击进入项目 这一次我们尝试一下略微复杂的c程序. 一.C程序 头文件: #ifndef __SAMPLE_H__ #define __SAMPLE_H__ #include <math.h&g ...