#!/usr/bin/env python
# -*- coding: utf-8 -*-


import threading
import time

value = 0
lock = threading.Lock()


def add():
global value
with lock:
new_value = value + 1
time.sleep(0.001)
value = new_value

if __name__ == '__main__':
threads = []
for i in range(100):
t = threading.Thread(target=add)
t.start()
threads.append(t)

for t in threads:
t.join()

print value
print 'Main end'



如果将with lock去掉,将得不到最终的值100.


相关文章:

  • 2022-12-23
  • 2021-11-18
  • 2021-10-16
  • 2022-12-23
  • 2021-08-15
  • 2021-11-21
  • 2021-11-18
猜你喜欢
  • 2022-02-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-26
  • 2022-12-23
  • 2022-12-23
  • 2021-12-21
相关资源
相似解决方案