多线程的锁:
由于并发的问题,需要加锁:当多个线程同时进行任务时,为了保证不会有多个线程同时对同一个数据进行操作造成不可预料的后果,所以有了锁的概念,我们通过锁来使多线程任务更加安全。
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()