import threading
VALUE = 0
def add_value():
#引用全局变量,并保证全局变量不被清零,使用global
global VALUE
for x in range(1000):
VALUE += 1
print('value:%d' % VALUE)
def main():
for x in range(2):
#创建两个线程
t = threading.Thread(target=add_value())
t.start()
if __name__ == '__main__':
main()
运行结果:
value:1000
value:2000
Process finished with exit code 0
多线程的加锁机制:LOCK
当VALUE的数据很大时,两个线程同时执行的概率就很大,导致计算不准确,以至于产生脏数据,所以对数据加锁是必要的
import threading
VALUE = 0
glock = threading.Lock()
def add_value():
global VALUE
# acquire函数进行加锁
glock.acquire()
for x in range(1000):
VALUE += 1
# release函数进行解锁
glock.release()
print('value:%d' % VALUE)
def main():
for x in range(2):
t = threading.Thread(target=add_value())
t.start()
if __name__ == '__main__':
main()