信号量
让多个线程操作数据
当资源释放时计数器就会递增,当资源申请时计数器就会递减。
下面展示一些 内联代码片
。
// A code block
var foo = 'bar';
//
def run(n,x): #重写
if semaphore.acquire(): #加锁获取信号量
print(n)
time.sleep(x)
semaphore.release() #解锁释放信号量
if __name__== "__main__": #主线程
semaphore = threading.Semaphore(5)#定义信号量
all_thread = []
for i in range(50):
t = threading.Thread(target=run,args=(i,i))
t.start()
条件变量
条件变量提供了对复杂线程同步问题的支持,也是使用互斥锁实现的,主要是两层锁结构 con = threading.Condition()
wait():条件不满足时调用,线程会释放锁并进入等待阻塞;
notify():条件创造后调用,通知等待池激活一个线程;
notifyAll():条件创造后调用,通知等待池激活所有线程
// A code block
var foo = 'bar';
//
import time
import threading
def run(x): #重写
con.acquire()
print(f'线程{x}')
con.notify()
print(f'线程{x}挂起')
con.wait()
time.sleep(2)
print(f'线程{x}再次启动')
con.notify()
con.release() #解锁释放信号量
def run2(x): #重写
con.acquire()
print(f'线程{x}')
con.notify()
print(f'线程{x}挂起')
con.wait()
time.sleep(2)
print(f'线程{x}再次启动')
con.notify()
con.release() #解锁释放信号量
if __name__== "__main__": #主线程
con = threading.Condition()#定义信号量
t1 = threading.Thread(target=run,args=(1,))
t1.start()
t2 = threading.Thread(target=run,args=(2,))
t2.start()
事件
线程事件用于线程控制线程,实现多个进程间的交互
// A code block
var foo = 'bar';
//
import time
import threading
def car():
while True:
if event.is_set():
print("小车行驶")
else
print("小车停止")
event.wait()
def set_event():
while True:
event.set()
time.sleep(1)
event.clear()
time.sleep(1)
if __name__== "__main__": #主线程
event = threading.Event()#定义信号量
car1 = threading.Thread(target=car)
car1.start()
set_e = threading.Thread(target=set_event)
set_e.start()