Python的互斥锁

想知道一些原理,建议去学操作系统

from threading import *

num = 0
# 创建锁对象
lock = Lock()
def task1():
    # 上锁
    lock.acquire()
    global num
    for i in range(1000000):
        num += 1
    print('task1',num)
    # 解锁
    lock.release()

def task2():
    lock.acquire()
    global num
    for i in range(1000000):
        num += 1
    print('task2',num)
    lock.release()

if __name__ == '__main__':
    t1 = Thread(target=task1)
    t2 = Thread(target=task2)
    t1.start()
    # 也可以通过join方法解决全局变量共享造成的错误
    # t1.join()
    t2.start()

posted @ 2021-03-09 18:21  code-G  阅读(84)  评论(0编辑  收藏  举报