from threading import Thread,Lock
import os,time
#互斥锁
def work():
global n
lock.acquire() # 锁住n,让他依次执行
temp = n
print(n)
time.sleep(0.1)
n=temp-1
print(n)
lock.release() #释放锁
if __name__ == '__main__':
lock=Lock()
n = 100
l = []
for i in range(100):
p=Thread(target=work)
l.append(p)
p.start()
for p in l:
p.join()
import threading
import time
# 递归锁
#RLcok类的用法和Lock类一模一样,但它支持嵌套,在多个锁没有释放的时候一般会使用RLcok类。
def Fun(lock):
global gl_num
lock.acquire()
gl_num += 1
time.sleep(1)
print(gl_num)
lock.release()
if __name__ == '__main__':
gl_num = 0
lock = threading.RLock()
for i in range(10):
t = threading.Thread(target=Fun,args=(lock,))
t.start()
import threading
import time
#信号量(BoundedSenaohore类)
def run(n, semaphore):
semaphore.acquire() #加锁
time.sleep(1)
print("run the thread:%s\n" %n)
semaphore.release() #释放锁
if __name__ == '__main__':
num = 0
semaphore = threading.BoundedSemaphore(5) #最多允许5个线程同时运行
for i in range(22):
#print(i)
t = threading.Thread(target=run,args=("t-%s" % i, semaphore))
t.start()
while threading.active_count() !=1:
print("while",threading.active_count())
else:
print('-----all threads done----')
import threading
import time
"""
事件(Event类)
python线程的事件用于主线程控制其他线程的执行,事件是一个简单的线程同步对象,其主要提供以下几个方法:
clear 将flag设置为“False”
set 将flag设置为“True”
is_set 判断是否设置了flag
wait 会一直监听flag,如果没有检测到flag就一直处于阻塞状态
事件处理的机制:全局定义了一个“Flag”,当flag值为“False”,那么event.wait()就会阻塞,当flag值为“True”,那么event.wait()便不再阻塞。
"""
#利用Event类模拟红绿灯
event = threading.Event()
def lighter():
count = 0
event.set() #初始值为绿灯
while True:
if 5 < count <= 10:
event.clear() #红灯,清除标志位
print("\33[41;1mred light is on..\033[0m")
elif count > 10:
event.set() #
count = 0
else:
print("\33[42;1mgreen light is on...\033[0m")
time.sleep(1)
count += 1
def car(name):
while True:
if event.is_set(): #判断是否设置了标志位
print("[%s] running..."%name)
time.sleep(1)
else:
print("[%s] sees red light,waiting...."%name)
event.wait()
print("[%s] green light is on,start going... "%name)
light = threading.Thread(target=lighter)
light.start()
car = threading.Thread(target=car,args=("MINI",))
car.start()