在python中,当开启多个线程对同一个变量进行操作,如果不加上线程锁,那么变量的值就不能同步
例如在线程1中对a的取值为1,在线程二中对a的取值为2,在线程中打印a的值,这两个值就不能同步。
示例代码为:
import threading
lock = threading.Lock()
def thread_task():
with lock: # do something pass
threads = []
for _ in range(50):
t = threading.Thread(target=thread_task)
t.start()
threads.append(t)
for t in threads:
t.join()