1 互斥锁(同步锁)
#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/5/9
import time
import threading
def addNum():
global num # 在每个线程中都获取这个全局变量
Lock.acquire() # 每次只能有一个线程在运行Lock块的代码
temp = num
time.sleep(0.01)
num = temp - 1 # 对此公共变量进行-1操作
Lock.release()
num = 100 # 设定一个共享变量
Lock = threading.Lock() # 定义同步锁
thread_list = []
for i in range(100):
t = threading.Thread(target=addNum)
t.start()
thread_list.append(t)
for t in thread_list: #等待所有线程执行完毕
t.join()
print('Result: ', num)#!/usr/bin/env python
# __Author__