Python--线程锁及生产者消费者模式

线程锁:
当多个线程同时进行任务时,为了保证不会有多个线程同时对同一个数据进行操作造成不可预料的后果,所以有了锁的概念,我们通过锁来使多线程任务更加安全。
获取锁:lock=threading.Lock()
cond=threading.Condition(lock=lock)
为了更精确的控制锁,提供了四个方法:
上锁:acquire(),等待:wait(),解锁:release(),唤醒:notify()或notify_all()。

实例:
import threading
import time
class Thread1(threading.Thread):
    def run(self):
        for i in range(1,11):
            if i==3:
                cond.acquire()#上锁
                cond.wait()#等待
                cond.release()#解锁
            print(i)
            time.sleep(1)
class Thread2(threading.Thread):
    def run(self):
        for i in range(30,19,-1):
            print(i)
            time.sleep(1)
        cond.acquire()
        cond.notify()#唤醒
        cond.release()
lock=threading.Lock()
cond=threading.Condition(lock=lock)
t1=Thread1()
t2=Thread2()
t1.start()
t2.start()


生产者和消费者模式:
某个模块负责产生数据,这些数据由另一个模块来负责处理。产生数据的模块,就形象地称为生产者;而处理数据的模块,就称为消费者。
该模式还需要有一个缓冲区处于生产者和消费者之间,作为一个中介。生产者把数据放入缓冲区,而消费者从缓冲区取出数据。
生产者是一堆线程,消费者是另一堆线程,内存缓冲区可以使用list数组队列。数据类型只需要定义一个简单的类就好。
最关键的就是内存缓冲区为空的时候消费者必须等待,而内存缓冲区满的时候,生产者必须等待。

实例:
import threading
import time
list=[]
lock=threading.Lock()
huofuCond=threading.Condition(lock=lock)
lock2=threading.Lock()
chihuoCond=threading.Condition(lock=lock2)
class Huofu(threading.Thread):
    def run(self):
        while True:
            chihuoCond.acquire()
            for i in range(1,21):
                list.append(i)
                print("伙夫生产第{0}个馒头".format(i))
                time.sleep(0.5)
            #等待
            huofuCond.acquire()
            chihuoCond.notify_all()
            chihuoCond.release()
            huofuCond.wait()
            huofuCond.release()
mantou=None
class Chihuo(threading.Thread):
    def __init__(self,name=None):
        threading.Thread.__init__(self)
        self.name=name
    def run(self):
        while True:
            chihuoCond.acquire()
            if len(list)==0:
                huofuCond.acquire()
                huofuCond.notify()
                huofuCond.release()
                chihuoCond.wait()
            chihuoCond.release()
            chihuoCond.acquire()
            if len(list)>0:
                mantou=list.pop()
                print("{0}在吃第{1}个馒头".format(threading.current_thread().name,mantou))
                time.sleep(0.5)
            chihuoCond.release()
hf=Huofu()
a=Chihuo("瑞克")
b=Chihuo("萨姆")
c=Chihuo("迪恩")
hf.start()
a.start()
b.start()
c.start()


正则表达式(.*)和(.*?)的区别:
.*?是懒惰模式:a.*?b匹配最短的,以a开始,以b结束的字符串。如果把它应用于aabab的话,它会匹配aab(第一到第三个字符)和ab(第四到第五个字符)。
.*是贪婪模式:以这个表达式为例:a.*b,它将会匹配最长的以a开始,以b结束的字符串。如果用它来搜索aabab的话,它会匹配整个字符串aabab。这被称为贪婪匹配。















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值