#!_*_coding:utf-8_*_
#__author__:"hkey"
import threading
balance = 0
def run_thread(lock, n):
lock.acquire()
global balance
for i in range(10000000):
balance = balance + n
balance = balance - n
lock.release()
if __name__ == '__main__':
lock = threading.Lock()
t1 = threading.Thread(target=run_thread, args=(lock, 5))
t2 = threading.Thread(target=run_thread, args=(lock, 8))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)
输出结果:
0
多线程锁总结:在多线程编程中,无论是变量的计算还是写入同一个文件都要加锁,使用多线程编程一定要注意锁的使用。