标签:append targe lock nbsp lease nal 共享变量 bsp import
import time
import threading
def addNum():
    #在每个线程中都获取这个全局变量
    global num
    temp = num
    time.sleep(0.1)
    #对此公共变量进行-1操作
    num = temp-1
#设定一个共享变量
num = 100
thread_list = []
for i in range(100):
    t = threading.Thread(target=addNum)
    t.start()
    thread_list.append(t)
#等待所有线程执行完毕
for t in thread_list:
    t.join()
print(‘final num:‘, num )
输出:
99
 
import time
import threading
def addNum():
    global num
    lock.acquire()
    temp = num
    time.sleep(0.1)
    num = temp-1
    lock.release()
num = 100
thread_list = []
lock = threading.Lock()
for i in range(100):
    t = threading.Thread(target=addNum)
    t.start()
    thread_list.append(t)
for t in thread_list:
    t.join()
print(‘final num:‘, num )
输出:
0
标签:append targe lock nbsp lease nal 共享变量 bsp import
原文地址:https://www.cnblogs.com/dongmengze/p/9559660.html