线程同步
Lock(线程锁)
- 导入Lock方法
from threading import Lock
lock=Lock()
- Lock的使用
lock.acquire() 线程的获取
lock.release() 线程的释放
实例:
- 全局变量及库的导入
import threading
from threading import Lock
lock = threading.Lock()
total = 0
- 函数的编写
def function_add():
global total
# with lock:
lock.acquire()
for i in range(10000000):
total += 1
lock.release()
def function_del():
global total
# with lock:
#用于获取线程
lock.acquire()
for i in range(10000000):
total -= 1
#用于释放线程
lock.release()
- 主函数的编写
if __name__ == "__main__":
thread1 = threading.Thread(target=function_add, args=())
thread2 = threading.Thread(target=function_del, args=())
thread1.start()
thread2.start()
#join()函数保证函数线程运行完成再向下执行
thread1.join()
thread2.join()
print(total)
总结:调试发现total的值不为0,说明存在线程不同步现象,因为pythonGIL的原因,一个线程只能运行一个函数,因此在线程加锁之后的运行结果为理论值0.否则不用线程锁结果为非0的数值4。
此外:还可用with lock来替换lock.acquire()和lock.release()方法