from threading import Thread import os,time n=100 def work(): global n temp=n time.sleep(0.1) n=temp-1 l=[] for i in range(100): p=Thread(target=work) l.append(p) p.start() for p in l: p.join() print(n) #结果可能为99
macname@MacdeMacBook-Pro py % python3 cccccc.py 99 macname@MacdeMacBook-Pro py %
from threading import Thread, Lock import os, time n = 100 def work(): global n lock.acquire() temp = n time.sleep(0.1) n = temp - 1 lock.release() if __name__ == '__main__': lock = Lock() l = [] for i in range(100): p = Thread(target=work) l.append(p) p.start() for p in l: p.join() print(n) #0
macname@MacdeMacBook-Pro py % python3 cccccc.py 0 macname@MacdeMacBook-Pro py %