多线程同时运行,能提高程序的运行效率,但是并非线程越多越好,而semaphore信号量可以通过内置计数器来控制同时运行线程的数量,启动线程(消耗信号量)内置计数器会自动减一,线程结束(释放信号量)内置计数器会自动加一;内置计数器为零,启动线程会阻塞,直到有本线程结束或者其他线程结束为止。
semaphore信号量相关函数介绍acquire() — 消耗信号量,内置计数器减一;
release() — 释放信号量,内置计数器加一;
在semaphore信号量有一个内置计数器,控制线程的数量,acquire()会消耗信号量,计数器会自动减一;release()会释放信号量,计数器会自动加一;当计数器为零时,acquire()调用被阻塞,直到release()释放信号量为止。
按步骤解释信号量的使用:
# 导入线程模块
import threading
# 导入时间模块
import time
class Mythread(threading.Thread):
def __init__(self,num):
super(Mythread, self).__init__()
self.num=num
def run(self):
if semaphore.acquire():#计时器获取信号(数)量,相当于加上了一把锁
print("线程",self.num)
time.sleep(1)
semaphore.release()#五个信号量同时释放
if __name__=="__main__":#主线程
semaphore=threading.Semaphore(5)#添加一个计数器,最大并发线程数量5(最多同时运行5个线程)
all_thread=[]#创建一个列表
for i in range(100):
all_thread.append(Mythread (str(i)))#把每次建立的线程存到列表里
for j in all_thread:#以列表为原始循环,一个一个取出来
j.start()
学习笔记二:条件变量
python 条件变量Condition也需要关联互斥锁,同时Condition自身提供了wait/notify/notifyAll方法,用于阻塞/通知其他并行线程,可以访问共享资源了。可以这么理解:Condition提供了一种多线程通信机制,假如线程1需要数据,那么线程1就阻塞等待,这时线程2就去制造数据,线程2制造好数据后,通知线程1可以去取数据了,然后线程1去获取数据。
按步骤解释条件变量的使用:# 导入线程模块
import threading
# 创建条件变量condition
con = threading.Condition()
def thread_one(name):
# 条件变量condition 线程上锁
con.acquire()
print("")
# 唤醒正在等待(wait)的线程
con.notify()
# 等待对方回应消息,使用wait阻塞线程,等待对方通过notify唤醒本线程
con.wait()
print("")
# 唤醒对方
con.notify()
# 等待消息答应
con.wait()
print("")
# 唤醒对方
con.notify()
# 等待消息答应
con.wait()
print("")
# 唤醒对方
con.notify()
# 条件变量condition 线程释放锁
con.release()
#def thread_one(name):与一类似
if __name__ == "__main__":
# 创建并初始化线程
t1 = threading.Thread(target=thread_one,args=("A"))
t2 = threading.Thread(target=thread_two,args=("B"))
# 启动线程 -- 注意线程启动顺序,启动顺序很重要
t2.start()
t1.start()
# 阻塞主线程,等待子线程结束
t1.join()
t2.join()
print("程序结束!")
学习笔记三:事件
一个线程发出事件信号,而其他线程等待该信号。
按步骤解释事件的使用:
import threading
import time
class examine(threading.Thread):
def __init__(self,time):
super(examine, self).__init__()
self.time=time
def run(self):
while True:
print(time.strftime("%H:%M:%S", time.localtime())) # 格式化输出当前的时分秒
time.sleep(3) # 输出的间隔时间为3秒
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()
examine=examine(str(time.localtime()))
set_event_=set_event()
examine.start() #启动线程
set_event_.start()



