Python进程及线程编程(4)

#!_*_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

多线程锁总结:在多线程编程中,无论是变量的计算还是写入同一个文件都要加锁,使用多线程编程一定要注意锁的使用。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/065d8208ae91fda8e3f9161255ad5f63.html