Python之Lock锁

python中的锁lock=threading.Lock()
避免多个线程保卫同一块数据的时候,产生错误,所以加锁来防止这种问题

import threading
import time
from queue import Queue
def a():
    global A,lock
    lock.acquire()
    for i in range(10):
        A+=1
        print("a",A)
    lock.release()
def b():
    global A,lock
    lock.acquire()
    for i in range(10):
        A+=10
        print("b",A)
    lock.release()

if __name__ == '__main__':
    lock = threading.Lock()
    A=0
    t1=threading.Thread(target=a,)
    t2=threading.Thread(target=b,)
    t1.start()
    t2.start()
输出结果:
a 1
a 2
a 3
a 4
a 5
a 6
a 7
a 8
a 9
a 10
b 20
b 30
b 40
b 50
b 60
b 70
b 80
b 90
b 100
b 110

你可能感兴趣的:(多线程编程私人笔记,多线程,python)