python-多线程-共享变量问题

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)

 

你可能感兴趣的:(python)