import threading import time #某段代码只能单线程执行时,上锁,其他线程等待,直到释放锁后,其他线程再争锁,执行代码,释放锁 locka = threading.Lock() a = 0 def add1(): global a try: locka.acquire() # 获得锁 tmp = a + 1 time.sleep(0.2) # 延时0.2秒,模拟写入所需时间 a = tmp finally: locka.release() # 释放锁 print('%s adds a to 1: %d'%(threading.current_thread().getName(),a)) threads = [threading.Thread(name='t%d'%(i,),target=add1) for i in range(10)] [t.start() for t in threads]