import threading,time,random,contextlib
onelock=threading.Lock()
class LockSingleton():
def __call__(self):return onelock
LockSingleton()()
def inc(lok):
try:
with lok():v=float(random.randint(0,10));v=v/10;alll.append(v);v+=c.value;time.sleep(v);c.value=v
except:
v=float(random.randint(0,10));v=v/10;alll.append(v);v+=c.value;time.sleep(v);c.value=v
for i in [LockSingleton(),contextlib.suppress,threading.Lock,"nolock"]:
alll=[]
c=type("Counter", (object,), dict(value=0))
threads=[]
for f in range(5):
t = threading.Thread(target=inc,args=(i,));t.start()#t.join() joining must be when both are running
threads.append(t)
for i in threads:t.join()
print(sorted(alll))
print(sum(alll))
print(c.value)
将所有随机值相加得到总和,一个接一个地执行(这里带锁,这里是单例)就可以不加锁(空上下文contextlib.suppress())
附加值越大,时间越长。sleep是,因为我在那里放置的秒数与附加值一样大
更长的睡眠时间没关系,因为添加了其他线程的睡眠吗?如果这样做的话,只有最大的随机值会加到c.value