当前位置:首页 » python教程 » 正文

Python semaphore evevt生产者消费者模型原理解析

看: 906次  时间:2020-08-03  分类 : python教程

线程锁相当于同时只能有一个线程申请锁,有的场景无数据修改互斥要求可以同时让多个线程同时运行,且需要限制并发线程数量时可以使用信号量

import threading, time, queue

def test(name):
  semaphore.acquire() #获取信号量锁
  print('my name is %s' %name)
  time.sleep(1)
  semaphore.release() #释放信号量锁

semaphore = threading.BoundedSemaphore(5) #创建一个信号量同时可以运行3个线程
for i in range(20):
  t = threading.Thread(target=test, args=(i,))
  t.start()
while threading.active_count() == 1:
  print("all run done")

两个或者多个线程需要交互时,且一个进程需要根据另一线程状态执行对应操作时,可以通过event来设置线程状态达到期望的效果,下面是一个红绿灯的例子

event = threading.Event() #实例化一个event
def light():
  while True:
    print("红灯亮了,请停车")
    time.sleep(20) #开始是红灯20s
    event.set() #红灯时间到了,设置标志位
    print("绿灯亮了,请通行")
    time.sleep(30) #持续30s红灯
    event.clear() #清空标志位

def car(num):
  while True:
    if event.is_set():#检测event被设置则执行
      print("car %s run"%num)
      time.sleep(5)
    else:
      print("this is red light waiting")
      event.wait() #此处会卡主,直到状态被设置才会向下执行



Light = threading.Thread(target=light,)
Light.start()
for i in range(10):
  Car = threading.Thread(target=car, args=(i,))
  Car.start()

当多个线程需要交互数据可以使用queue来进行数据传递,下面是经典的生产者消费者多线程模型示例,其中包含线程queue的基本使用方法

my_queue = queue.Queue() #实例化一个队列
queue1 = queue.LifoQueue() #后进 先出队列
queue2 = queue.PriorityQueue() #带优先级的队列
def pro():
  for i in range(100):
    my_queue.put(i) #队列里面放数据
def con():
  while my_queue.qsize() > 0: #当队列有数据时候从队列取数据
    print("i an a consumer,get num %s"%my_queue.get(timeout=3))
    time.sleep(2)
  else:
    print("my queue is empty")

Pro = threading.Thread(target=pro)
Pro.start()


for j in range(10):
  Con = threading.Thread(target=con)
  Con.start()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持python博客。

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!