python多线程同步机制Lock

#!/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.


posted @ 2017-09-24 10:59  泽锦  阅读(346)  评论(0编辑  收藏  举报