多线程的锁

多线程的锁:

由于并发的问题,需要加锁:

当多个线程同时进行任务时,为了保证不会有多个线程同时对同一个数据进行操作造成不可预料的后果,所以有了锁的概念,我们通过锁来使多线程任务更加安全。

lock = threading.Lock()

cond = threading.Condition(lock=lock)

多线程的锁实例:

import threading
import time

lock=threading.Lock()
cond=threading.Condition(lock=lock)

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()


t1=Thread1()
t2=Thread2()
t1.start()
t2.start()

Condition:更精确的控制锁,提供了四个方法:

acquice()   上锁

wait()        等待

release()   解锁

notify()     唤醒         notify_all()  唤醒全部

生产者和消费者模式(吃货与伙夫):

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()
haha=Chihuo("哈哈")
heihei=Chihuo("嘿嘿")
xixi=Chihuo("嘻嘻")
hf.start()
haha.start()
heihei.start()
xixi.start()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值