zoukankan      html  css  js  c++  java
  • 【python学习】多线程锁 生产者和消费者问题

     1 #!/usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 
     4 import threading
     5 import random, time, Queue
     6 
     7 MAX_SIZE = 5
     8 SHARE_Q = []  #模拟共享队列
     9 CONDITION = threading.Condition()
    10 
    11 class Producer(threading.Thread) :
    12 
    13     def run(self) :
    14         products = range(5)
    15         global SHARE_Q
    16         while True :
    17             CONDITION.acquire()
    18             if len(SHARE_Q) == 5 :
    19                 print "Queue is full.."
    20                 CONDITION.wait()
    21                 print "Consumer have comsumed something"
    22             product = random.choice(products)
    23             SHARE_Q.append(product)
    24             print "Producer : ", product
    25             CONDITION.notify()
    26             CONDITION.release()
    27             time.sleep(random.random())
    28 
    29 class Consumer(threading.Thread) :
    30 
    31     def run(self) :
    32         global SHARE_Q
    33         while True:
    34             CONDITION.acquire()
    35             if not SHARE_Q :
    36                 print "Queue is Empty..."
    37                 CONDITION.wait()
    38                 print "Producer have producted something"
    39             product = SHARE_Q.pop(0)
    40             print "Consumer :", product
    41             CONDITION.notify()
    42             CONDITION.release()
    43             time.sleep(random.random())
    44 
    45 def main() :
    46     producer = Producer()
    47     consumer = Consumer()
    48     producer.start()
    49     consumer.start()
    50 
    51 if __name__ == '__main__':
    52     main()

    Condition

    条件变量中有acquire()和release方法用来调用锁的方法, 有wait(), notify(), notifyAll()方法, 后面是三个方法必须在获取锁的情况下调用, 否则产生RuntimeError错误.

    • 当一个线程获得锁后, 发现没有期望的资源或者状态, 就会调用wait()阻塞, 并释放已经获得锁, 知道期望的资源或者状态发生改变
    • 当一个线程获得锁, 改变了资源或者状态, 就会调用notify()和notifyAll()去通知其他线程,
  • 相关阅读:
    MySql存储引擎MyISAM和InnoDB的区别
    Nginx下载安装
    科目三考试训练大纲
    解决The current branch is not configured for pull No value for key branch.master.merge found in config
    java实现截取6个汉字字母数字
    如何将git上的代码迁移到Coding上
    Python抓取博客园首页文章列表(带分页)
    Python实现抓取CSDN博客首页文章列表
    Python实现抓取CSDN热门文章列表
    linux目录的操作
  • 原文地址:https://www.cnblogs.com/fjl-vxee/p/6690947.html
Copyright © 2011-2022 走看看