欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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)