笔记本📒

python互斥锁的使用

2021-01-18  本文已影响0人  涓涓自然卷

知识要点

1、互斥锁的创建:mutex = threading.Lock()
2、上锁:mutex.acquire()
3、释放锁:mutex.release()

代码🌰

import threading


# 全局变量
g_num = 0


# 对g_num进行加操作
def sum_num1():
    # 上锁
    mutex.acquire()

    for i in range(1000000):
        global g_num
        g_num += 1

    # 解锁
    mutex.release()
    print("g_num1:", g_num)


# 对g_num进行加操作
def sum_num2():
    # 上锁
    mutex.acquire()

    for i in range(1000000):
        global g_num
        g_num += 1

    # 解锁
    mutex.release()

    print("g_num2:", g_num)


if __name__ == '__main__':
    # 创建锁
    mutex = threading.Lock()
    # 创建子进程
    sum1_thread = threading.Thread(target=sum_num1)
    sum2_thread = threading.Thread(target=sum_num2)

    # 启动线程
    sum1_thread.start()
    sum2_thread.start()

运行结果

可以正确运行出结果:


image.png
上一篇 下一篇

猜你喜欢

热点阅读