信号量:所谓信号,类似于道路上的信号灯,一种用来标识等待还是通过的标志。绿灯通过,红灯等待。道路中通过信号灯的颜色标识通过和等待,而Dispatch Semaphore中通过“计数”来标识通过和等待。(假设同时进行5个线程,其中一个线程结束后面线程会补进来)
条件变量:Condition(条件变量)通常与一个锁关联。需要在多个Contidion中共享一个锁时,可以传递一个Lock/RLock实例给构造方法,否则它将自己生成一个RLock实例。(可以在执行一个线程的中途执行第二个事件)
- acquire(): 线程锁
- release(): 释放锁
- wait(timeout): 线程挂起,直到收到notify
- notify(): 通知其他线程,那些挂起的线程接到这个通知之后会开始运行
- notifyAll(): 如果wait状态线程比较多,notifyAll的作用就是通知所有线程
事件:在函数计算服务中使用Python编程,需要定义一个函数作为入口函数,本文介绍Python事件函数。
信号量
#信号量
import threading
import time
class Thread(threading.Thread):
def __init__(self,num):
super(Thread, self).__init__()#继承
self.num=num
def run(self):
semaphore.acquire()#获取锁,信号量
print(self.num)
time.sleep(self.num)
semaphore.release()#释放锁,信号量
if __name__ =="__main__":
event=threading.Event()
semaphore = threading.Semaphore(5)#信号量同时允许5个
for i in range(10):
t=Thread(i)
t.start()
条件变量
import threading
import time
class Thread(threading.Thread):
def __init__(self,name):
super(Thread, self).__init__()
self.name=name
def run(self):
condition.acquire()#获取
print("开始"+self.name)
condition.notify()#警示下一线程准备
time.sleep(1)
condition.wait()#等待警示
print("结束" + self.name)
time.sleep(1)
condition.notify()#警示下一线程
condition.release()#释放
if __name__ =="__main__":
condition=threading.Condition()
t1=Thread("H")
t2 = Thread("HHH")
t1.start()#线程1
t2.start()#线程2
输出结果(线程1启动进入等待,然后线程二运行进入等待,线程一结束,线程二结束)
事件
import threading
import time
class Thread(threading.Thread):
def __init__(self):
super(Thread, self).__init__()
def run(self):
while True:
if event.is_set():
print('运行中')
else:
print('停止')
event.wait()
class set_event(threading.Thread):
def __init__(self):
super(set_event, self).__init__()
def run(self):
while True:#循环判断事件的状态
event.set()#事件设立
time.sleep(1)
event.clear()#事件清理
time.sleep(1)
if __name__ =="__main__":
event=threading.Event()
e1=set_event()
e1.start()#线程启动
t=Thread()
t.start()