多线程同步
"""
因为python自带解释器锁GIL,所以我们用下面这种方式测试,当cpu运算速度达到一定数值,才会释放解释器锁
下面的例子,不加锁时,运算打印的num是小于2000000,因为多线程运行时num数据不安全
加锁后,num == 2000000
如何加锁?
lock.acquire() # 请求得到锁
...
lock.release() # 释放锁
"""
import threading
num = 0
lock = threading.Lock()
def task1():
lock.acquire()
global num
for i in range(1000000):
num += 1
lock.release()
if __name__ == '__main__':
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task1)
t1.start()
t2.start()
t1.join()
t2.join()
print(num)