码迷,mamicode.com
首页 > 编程语言 > 详细

线程同步应用

时间:2020-04-12 00:10:45      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:线程   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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!