线程锁

线程锁


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

lock=threading.Lock()

cond=threading.Condition(lock=lock)


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

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

生产者与消费者实例


import threading
import time
lock = threading.Lock()
HuoFuCond = threading.Condition(lock=lock)
lock2=threading.Lock()
ChiHuoCond = threading.Condition(lock=lock2)
list=[]
class HuoFu(threading.Thread):
    def run(self):

        while True:
            ChiHuoCond.acquire()
            for i in range(1,11):
                list.append(i)
                print("伙夫生产第{0}个馒头".format(i))
                time.sleep(0.2)
            #等待
            HuoFuCond.acquire()
            ChiHuoCond.notify_all()
            ChiHuoCond.release()
            HuoFuCond.wait()
            HuoFuCond.release()

ManTou=None
class ChiHuo(threading.Thread):
    def __init__(self,name):
        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.2)
            ChiHuoCond.release()
hf=HuoFu()
haha=ChiHuo("哈哈")
heihei=ChiHuo("嘿嘿")
hehe=ChiHuo("呵呵")
hf.start()
haha.start()
heihei.start()
hehe.start()








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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值