并发 :线程间同步、锁、可重入锁及互斥锁

2020-07-19  本文已影响0人  dex0423

线程间同步

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()

。。

上一篇下一篇

猜你喜欢

热点阅读