锁机制实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

import threading
import time

def (cond,name):
cond.acquire() # 申请
print(name+" I am run1,1")
cond.notify() # 唤起run2_1
cond.wait() # 阻塞本线程


print(name+"I am run1,2")
cond.notify() #唤起run2_2
cond.wait()

def run2(coda,name):
cond.acquire() # 申请
print(name+" I am run2,1")
cond.notify() # 唤起run1_2
cond.wait() # 阻塞本线程

print(name+"I am run2,2")
cond.notify()
cond.release()

cond = threading.Condition()
t1 = threading.Thread(target=run1,args=(cond,"xiaoyi",))
t2 = threading.Thread(target=run2,args=(cond,"xiaohuang"))
t1.start()
t2.start()
t1.join()
t2.join()