美文网首页
并发 :线程间同步、锁、可重入锁及互斥锁

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

作者: dex0423 | 来源:发表于2020-07-19 00:46 被阅读0次

    线程间同步

    • 线程间同步涉及线程互斥锁;
    • 锁(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()
    

    。。

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/dggqkktx.html