threading.Lock()
是Python中的线程锁,用于在多线程程序中控制线程对共享资源的访问。当一个线程获得了锁之后,其他线程需要等待这个线程释放锁之后才能继续访问共享资源。
下面是threading.Lock()
的基本用法示例:
import threading
# 创建一个Lock对象
lock = threading.Lock()
# 在需要保护共享资源的地方使用acquire()方法获取锁
lock.acquire()
try:
# 访问共享资源
print("Accessing shared resource")
finally:
# 使用完共享资源后释放锁
lock.release()
不用互斥锁的demo :
import threading
import time
lock = threading.Lock()
a = 1
def func1():
global a
while a < 20:
print(a, end=', ')
a += 1
time.sleep(1)
def func2():
global a
while a < 20:
print(a, end=', ')
a += 1
time.sleep(1)
def func3():
global a
while a < 20:
print(a, end=', ')
a += 1
time.sleep(1)
th1 = threading.Thread(target=func1)
th2 = threading.Thread(target=func2)
th3 = threading.Thread(target=func3)
th1.start()
th2.start()
th3.start()
# 输出结果:1, 2, 3, 44, 4, , 777, , , 1010, , 10, 131313, , , 1616, 16, , 19, 19,
看得出,由于多线程同时访问同一个变量,变量的变化是随机和混乱的。
使用with方法的demo:
import threading
import time
lock = threading.Lock()
x = 0
def func_a():
global x
while True:
if x < 6:
with lock:
x += 1
print('func_a', x, end=', ')
time.sleep(0.5)
else:
break
def func_b():
global x
while True:
if x < 6:
with lock:
x += 1
print('func_b', x, end=', ')
time.sleep(0.5)
else:
break
# func_b 和 func_c 函数也相应地做相同的修改
def func_c():
global x
while True:
if x < 6:
with lock:
x += 1
print('func_c', x, end=', ')
time.sleep(0.5)
else:
break
# func_b 和 func_c 函数也相应地做相同的修改
th1 = threading.Thread(target=func_a)
th2 = threading.Thread(target=func_b)
th3 = threading.Thread(target=func_c)
th1.start()
th2.start()
th3.start()
# 输出:func_a 1, func_b 2, func_c 3, func_a 4, func_b 5, func_c 6,
有了互斥锁后,线程对变量的访问是唯一和有序的。
使用lock.acquire()和lock.release()的demo:
import threading
import time
lock = threading.Lock()
def func_a():
global x
while True:
if x < 6:
lock.acquire()
try:
x += 1
print('func_a', x, end=', ')
finally:
lock.release()
time.sleep(0.5)
else:
break
def func_b():
global x
while True:
if x < 6:
lock.acquire()
try:
x += 1
print('func_b', x, end=', ')
finally:
lock.release()
time.sleep(0.5)
else:
break
def func_c():
global x
while True:
if x < 6:
lock.acquire()
try:
x += 1
print('func_c', x, end=', ')
finally:
lock.release()
time.sleep(0.5)
else:
break
th1 = threading.Thread(target=func_a)
th2 = threading.Thread(target=func_b)
th3 = threading.Thread(target=func_c)
th1.start()
th2.start()
th3.start()
# 输出:func_a 1, func_b 2, func_c 3, func_c 4, func_b 5, func_a 6,