同步锁

'''
GIL:全局解释锁
  因为有GIL,所以,同一时刻,只有一个线程被cpu执行
    处理方法:多进程+协程
任务种类:IO密集型
     计算密集型
对于IO密集型的任务,Python的多线程时有意义的
          可以采用多进程+协程
对计算密集型的任务,Python的多线程就不推荐,Python就不适用了
'''


#   同步锁
import threading
import time


def sub():
    global  num

    lock.acquire()  # 加同步锁
    temp = num
    time.sleep(0.0005)
    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 i in l:
    i.join()

print(num)

猜你喜欢

转载自www.cnblogs.com/lhqlhq/p/8990535.html