线程锁

线程锁

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

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

发表评论

电子邮件地址不会被公开。 必填项已用*标注