Python学习笔记:同步锁

# -*- encoding:utf-8 -*-
import threading
import time

def sub():
    global num
    # num-=1
    lock.acquire()  #获取锁,将lock中间包起来,执行中间部分的时候cpu不准轮询,只能串行
    temp=num
    time.sleep(0.001)
    num=temp-1
    lock.release()  #释放锁

num=100

l=[]
lock=threading.Lock()
for i in range(100):
    t=threading.Thread(target=sub)
    t.start()
    l.append(t)

for t in l:
    t.join()

print (num)

 

你可能感兴趣的:(Python学习笔记)