20190418
Posted pie-o
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)
以上是关于20190418的主要内容,如果未能解决你的问题,请参考以下文章