并发 :线程间同步、锁、可重入锁及互斥锁
2020-07-19 本文已影响0人
dex0423
线程间同步
- 线程间同步涉及线程互斥锁;
- 锁(Lock)容易导致死锁,可重入锁(RLock)则不会导致死锁,但每次 acquire 后都要 release;
import time
from threading import Thread, Lock
lock_1 = Lock()
lock_2 = Lock()
lock_3 = Lock()
lock_2.acquire()
lock_3.acquire()
num = 0
class Task1(Thread):
def run(self):
while 1:
if lock_1.acquire():
print("task 1 run ... plus 1")
global num
num += 1
print("num : ", num)
time.sleep(1)
lock_2.release()
class Task2(Thread):
def run(self):
while 1:
if lock_2.acquire():
print("task 2 run ... plus 2")
global num
num += 2
print("num : ", num)
time.sleep(1)
lock_3.release()
class Task3(Thread):
def run(self):
while 1:
if lock_3.acquire():
print("task 3 run ... plus 3")
global num
num += 3
print("num : ", num)
time.sleep(1)
lock_1.release()
def main():
# print("主进程开始")
# # 创建子进程
# p1 = Worker(3)
# p2 = Worker(1)
# p1.start()
# p2.start()
# p1.join()
# p2.join()
# print("主进程结束")
task1 = Task1()
task2 = Task2()
task3 = Task3()
task1.start()
task2.start()
task3.start()
if __name__ == '__main__':
main()
。。