-
Notifications
You must be signed in to change notification settings - Fork 0
/
py_thread_lock.py
42 lines (32 loc) · 1022 Bytes
/
py_thread_lock.py
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
33
34
35
36
37
38
39
40
41
42
import time
import threading
mutex_a = threading.Lock()
mutex_b = threading.Lock()
class MyThread(threading.Thread):
def task_a(self):
if mutex_a.acquire():
print("thread {} get mutex a ".format(self.name))
time.sleep(1)
if mutex_b.acquire():
print("thread {} get mutex b ".format(self.name))
mutex_b.release()
mutex_a.release()
def task_b(self):
if mutex_b.acquire():
print("thread {} get mutex b ".format(self.name))
time.sleep(1)
if mutex_a.acquire():
print("thread {} get mutex a ".format(self.name))
mutex_a.release()
mutex_b.release()
def run(self):
self.task_a()
self.task_b()
def main():
print("Start main threading")
threads = [MyThread() for i in range(3)]#thread3 得不到 任何
for t in threads:
t.start()
print("End Main threading")
if __name__=="__main__":
main()