第二曲
一个小栗子
# 多线程实现红绿灯
# 红灯绿灯亮5秒
import threading,time
event_flag = threading.Event() # 创建一个 Event() 对象
def lighter_status():
time_point = 0 # 记录时间
while True:
if time_point < 5:
event_flag.clear() # 清空 flag,代表红灯
print("\033[1;41m red light on... \033[0m")
time.sleep(1)
elif time_point >=5 and time_point < 10:
event_flag.set() # 创建 flag,代表绿灯
print("\033[1;42m green light on... \033[0m")
time.sleep(1)
else:
time_point = 0
time_point += 1
def car_status(car_name):
while True:
if event_flag.is_set():
print("[%s] is running ..." % car_name)
time.sleep(1)
else:
print("[%s] is waiting the red light ..." % car_name)
event_flag.wait() # 等待flag被设置
light_thread = threading.Thread(target=lighter_status)
baoma = threading.Thread(target=car_status,args=('baoma',))
tesla = threading.Thread(target=car_status,args=('tesla',))
light_thread.start() # 启动 红绿灯xianc
baoma.start() # 启动 车线程
tesla.start() # 启动 车线程
PS
:Event
类是对一个叫做 flag
标志位的封装,它的方法都是对flag
的操作,这个flag
相当于一个全局变 量,可以被所有的线程访问
set()
设置 flag
,相当于初始化一个flag
is_set()
判断 flag
是否被设置
clear()
清除 flag
wait()
如果flag
没有被设置就让线程等到flag
被设置再向下执行
Queue
import queue
# 普通队列 先进先出
q = queue.Queue(maxsize = 10)
for i in range(10):
q.put(i) # put 向队列里放对象
print(q.get())
print(q.get()) # get 取出一个对象
print(q.get())
# 后进先出队列 相当于栈
q = queue.LifoQueue(maxsize = 10)
for i in range(10):
q.put(i)
print(q.get())
print(q.get())
# 优先级队列,传入的对象按优先级排序,数字越小优先级越高
q = queue.PriorityQueue(maxsize = 10)
q.put((10,'bob'))
q.put((2,'alice'))
q.put((1,'Binary'))
print(q.get())
print(q.get())
又一个小栗子
# 生产者消费者
import queue,threading,time
q = queue.Queue(maxsize=5)
def productor(name):
while True:
if q.empty():
print("\033[1;41m [%s]开始生产...\033[0m" % name)
for i in range(5):
q.put('product'+str(i))
print('[%s] 生产了产品[%s]' % (name,i))
time.sleep(2)
else:
print("\033[1;42m 还有产品剩余...不生产... \033[0m")
time.sleep(1)
def consumer(name):
while True:
print("[%s] 消费了 [%s]" % (name,q.get()))
time.sleep(3)
p1 = threading.Thread(target=productor,args=('Binary',))
c1 = threading.Thread(target=consumer,args=('Joker',))
c2 = threading.Thread(target=consumer,args=('new_one',))
p1.start()
c1.start()
c2.start()