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