python 线程锁

"""
线程锁
我这用的是python3.7,必须要加锁才可以保证数据的确定性
"""
import time
from threading import Thread, Lock

lock = Lock()

list1 = [0] * 10


def task1():
    lock.acquire()  # 获取锁
    for i in range(len(list1)):
        list1[i] = 1
        print("设置list1")
        time.sleep(0.5)
    lock.release()  # 释放锁


def task2():
    lock.acquire()  # 获取锁
    for i in range(len(list1)):
        print("list1[i] =", list1[i])
        time.sleep(0.5)
    lock.release()  # 释放锁


if __name__ == ‘__main__‘:
    t1 = Thread(target=task1, name="task1")
    t2 = Thread(target=task2, name="task2")
    t1.start()
    t2.start()

    print("over")

相关推荐