python-多线程-共享变量问题
程序员文章站
2022-03-02 19:25:37
...
import threading
sum = 0
loopSum = 1000000
lock = threading.Lock()
def Add():
global sum, loopSum
for i in range(1,loopSum):
lock.acquire()
sum += 1
lock.release()
def Sub():
global sum,loopSum
for i in range(1,loopSum):
lock.acquire()
sum-=1
lock.release()
if __name__ == '__main__':
thread = threading.Thread(target=Add,args=())
thread1 = threading.Thread(target=Sub,args=())
thread.start()
thread1.start()
thread.join()
thread1.join()
print("sub 完成")
print(sum)
上一篇: Period