线程锁

from threading import Thread, Lock
import time

num = 0


# 线程一
def work_1():
    global num
    lock.acquire()
    for i in range(100000):
        num += 1
    lock.release()
    print("数据1是:", num)


# 线程二
def work_2():
    global num
    lock.acquire()  # 对这个线程进行上锁  当检测到有地方已经上锁了,那么这里等待锁被打开 才会执行下面的代码
    for i in range(100000):
        num += 1
    lock.release()  # 对这个线程进行解锁
    print("数据2是:", num)


if __name__ == '__main__':
    lock = Lock()
    t1 = Thread(target=work_1)
    t1.start()
    t2 = Thread(target=work_2)
    t2.start()
    print(num)

你可能感兴趣的:(线程锁)