python的并发GIL 了解

gil  又称 global interpreter lock (全局解释器锁)

#python 中一个线程对应于c语言中的一个线程

#gil使得同一个时刻只有一个线程在一个cpu上执行字节码,无法将多个线程映射到多个cpu上执行

#gil 会根据执行的字节码的行数,时间片过长的,io操作。

import dis

def add(a):

  a = a+1

  return a

print(dis.dis(add)) 

#验证gil锁,并没有是线程同步变的安全

扫描二维码关注公众号,回复: 2428104 查看本文章

total = 0

def add():

  global total

  for i in range(10000):

    total += 1

def desc():

  global total

  for i in range(10000):

    total -= 1

import threading

thread1=threading.Tread(target=add)

thread2=threading.Thread(target=desc)

thread1.start()

thread2.start()

thread1.join()

thread2.join()

猜你喜欢

转载自www.cnblogs.com/wuheng-123/p/9381793.html