temp = 0
num = 100
l = threading.Lock() #creat a LockObject
class foo(threading.Thread):
    def __init__(self):
        super(foo,self).__init__()
    def run(self):
        global temp,num,l
        print("ok")
        l.acquire()        '''
        temp = num           this part is locked
        time.sleep(0.0001) # 
        num = temp - 1
        l.release()       '''
        print(num)
threadlist = []
begin = time.time()
for i in range(50): # creat 50 threads and the total time is about 50*0.1
    t = foo()
    threadlist.append(t)
    t.start()
for t in threadlist:
    t.join()
end = time.time()
print(temp)
print(num)
print(end-begin)

把数据放在acquire 和release 之间,可以防止线程安全。当sleep足够趋近于0的时候,没有IOl阻碍,lock之前的执行后,执行locked ,当存在sleep时,取决于cpu的速度,(sleep(0,0001),output:okokokok99okok0kokokokokokok98)(sleep(0),  output:ok99ok98ok97)(sleep(1), output(okokoko...okok999897...50)

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。