码迷,mamicode.com
首页 > 其他好文 > 详细

20190418

时间:2019-04-18 18:49:35      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:tput   线程安全   div   kobject   about   time()   for   app   防止   

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)

20190418

标签:tput   线程安全   div   kobject   about   time()   for   app   防止   

原文地址:https://www.cnblogs.com/pie-o/p/10731399.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!