• python的并发GIL 了解


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

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

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

    #gil 会根据执行的字节码的行数,时间片过长的,io操作,释放会gil全局解释锁。

    import dis

    def add(a):

      a = a+1

      return a

    print(dis.dis(add)) 

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

    total = 0

    def add():

      global total

      for i in range(100000):

        total += 1

    def desc():

      global total

      for i in range(100000):

        total -= 1

    import threading

    thread1=threading.Tread(target=add)

    thread2=threading.Thread(target=desc)

    thread1.start()

    thread2.start()

    thread1.join()

    thread2.join()

     从 上面代码可以看出GiL不能保证线程安全,线程共享资源还是会抢占资源。

  • 相关阅读:
    macOS 修改键盘重复按键延迟
    stdout 与 stderr 区别
    E. 1-Trees and Queries
    Codeforces Round #615 (Div. 3)
    Codeforces Round 613(div 2)
    Codeforces Edu80
    SPOJ
    快读
    《货车运输》题解--最大生成树&倍增
    倍增思想求lca
  • 原文地址:https://www.cnblogs.com/wuheng-123/p/9381793.html
Copyright © 2020-2023  润新知