20190418

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)

posted @ 2019-04-18 18:20  pie_thn  阅读(87)  评论(0)    收藏  举报