线程同步应用

2021-02-20 09:17

阅读:635

标签:线程   class   run   div   time   star   lease   main   color   

 1 import time
 2 from threading import Thread,Lock
 3 #创建3把互斥锁
 4 lock1 = Lock()
 5 lock2 = Lock()
 6 lock3 = Lock()
 7 #对lock2和lock3上锁
 8 lock2.acquire()
 9 lock3.acquire()
10 
11 class Task1(Thread):
12     def run(self):
13         while True:
14             if lock1.acquire():
15                 print(...task1...)
16                 time.sleep(1)
17                 #释放lock2的锁
18                 lock2.release()
19 class Task2(Thread):
20     def run(self):
21         while True:
22             if lock2.acquire():
23                 print(...task2...)
24                 time.sleep(1)
25                 #释放lock3的锁
26                 lock3.release()
27 class Task3(Thread):
28     def run(self):
29         while True:
30             if lock3.acquire():
31                 print(...task3...)
32                 time.sleep(1)
33                 #释放lock1的锁
34                 lock1.release()
35 if __name__ == __main__:
36     t1 = Task1()
37     t2 = Task2()
38     t3 = Task3()
39     t1.start()
40     t2.start()
41     t3.start()
 1 ...task1...
 2 ...task2...
 3 ...task3...
 4 ...task1...
 5 ...task2...
 6 ...task3...
 7 ...task1...
 8 ...task2...
 9 ...task3...
10 ......

 

线程同步应用

标签:线程   class   run   div   time   star   lease   main   color   

原文地址:https://www.cnblogs.com/monsterhy123/p/12682935.html


评论


亲,登录后才可以留言!