多线程修改一份数据时需要用到线程锁,以防止数据修改出错
#-*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import threading import time num = 0 t_obj = [] lock = threading.Lock() #声明一个锁并赋给一个变量 def MyThread(n): lock.acquire() #给线程加锁 global num time.sleep(0.5) num +=1 lock.release() #释放给线程锁 for i in range(20): t = threading.Thread(target=MyThread,args=(i,)) t.start() t_obj.append(t) for t in t_obj: t.join() print("num:",num)