前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python3备份

Python3备份

作者头像
py3study
发布2020-01-02 17:51:04
3980
发布2020-01-02 17:51:04
举报
文章被收录于专栏:python3python3

Python3生产者/消费者模式

代码语言:javascript
复制
import threading  
import queue,time,random  
  
class Goods:#产品类  
    def __init__(self):  
        self.count = 0
    def add(self,num = 1):
        self.count += num  
    def sub(self):  
        if self.count>=0:  
            self.count -= 1  
    def empty(self):  
        return self.count <= 0

class Producer(threading.Thread):#生产者类  
    def __init__(self,condition,goods,sleeptime = 1):#sleeptime=1  
        threading.Thread.__init__(self)  
        self.cond = condition  
        self.goods = goods  
        self.sleeptime = sleeptime  
    def run(self):  
        cond = self.cond  
        goods = self.goods  
        while True:
            cond.acquire()#锁住资源  
            goods.add()
            print("产品数量:",goods.count,"生产者线程")
            cond.notifyAll()#唤醒所有等待的线程--》其实就是唤醒消费者进程 
            cond.release()#解锁资源
            time.sleep(self.sleeptime)

class Consumer(threading.Thread):#消费者类  
    def __init__(self,condition,goods,sleeptime = 2):#sleeptime=2  
        threading.Thread.__init__(self)
        self.cond = condition
        self.goods = goods
        self.sleeptime = sleeptime
    def run(self):  
        cond = self.cond
        goods = self.goods
        while True:
            time.sleep(self.sleeptime)
            cond.acquire()#锁住资源
            while goods.empty():#如无产品则让线程等待
                cond.wait()
            goods.sub()
            print("产品数量:",goods.count,"消费者线程")
            cond.release()#解锁资源  

g = Goods()
c = threading.Condition()
  
pro = Producer(c,g)  
pro.start()  
  
con = Consumer(c,g)  
con.start()  

Python的锁

代码语言:javascript
复制
import threading
import time

private_lock = threading.RLock()
num = 0


class MyThread(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.t_name = name 
        
    def run(self):
        global num
        while True:
            private_lock.acquire()
            if num > 4:
                print("%s" % self.t_name)
                time.sleep(5)
                private_lock.release()
                break
            num += 1
            private_lock.release()


def test1():
    thread1 = MyThread('A')
    thread2 = MyThread('B')
    thread1.start()
    thread2.start()


if __name__ == '__main__':
    test1()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Python3生产者/消费者模式
  • Python的锁
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档