zoukankan      html  css  js  c++  java
  • 【10.1】python中的GIL

     1 #!/user/bin/env python
     2 # -*- coding:utf-8 -*-
     3 
     4 # gil global interpreter lock(cpython)全局解释器锁
     5 # python中一个线程对应于c语言中的一个线程
     6 # gil时的同一时刻只有一个线程在一个cpu上执行字节码,无法将多个线程映射到多个cpu上执行
     7 # gil会根据执行的字节码行数以及时间片释放gil,gil在遇到io操作时主动释放
     8 import threading
     9 total = 0
    10 
    11 
    12 def add():
    13     global total
    14     for i in range(1000000):
    15         total += 1
    16 
    17 
    18 def desc():
    19     global total
    20     for i in range(1000000):
    21         total -= 1
    22 
    23 
    24 thread1 = threading.Thread(target=add)
    25 thread2 = threading.Thread(target=desc)
    26 
    27 thread1.start()
    28 thread2.start()
    29 
    30 thread1.join()
    31 thread2.join()
    32 
    33 print(total)
    C:UsersAdministratorPythonimooc>python demo.py
    -102343
    
    C:UsersAdministratorPythonimooc>python demo.py
    -29159
    
    C:UsersAdministratorPythonimooc>python demo.py
    -239340
    
  • 相关阅读:
    2017/4/14 afternoon
    2017/4/14 morning补
    2017/4/13 afternoon
    2017/4/13 morning
    2017/4/12 afternoon
    2017/4/12 morning
    4.17上午
    4.14上午
    4.13下午
    4.13上午
  • 原文地址:https://www.cnblogs.com/zydeboke/p/11294525.html
Copyright © 2011-2022 走看看