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()去通知其他线程,
  • 相关阅读:
    python2.7_1.4_将IPV4地址转换成不同的格式
    大型网站问题的解决方案
    大型网站的标准
    SCP服务实现Linux交互
    SCP服务实现Linux交互
    使用Linux系统中的SSH服务
    向php文件中添加php.ini文件
    让apache与mysql随着系统自动启动
    为apache与mysql创建快捷方式
    安装PHP软件
  • 原文地址:https://www.cnblogs.com/fjl-vxee/p/6690947.html
Copyright © 2011-2022 走看看