#!/usr/bin/env python# -*- coding: utf-8 -*- import threadingimport time value = 0lock = 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.
时间: 2024-10-08 22:48:46