特点:同一个时刻只有一个线程、无法将多个线程映射到多个cpu上执行、但并非没有作用、在io操作的时候是可以提高性能的。
证明gil不是一直锁着的:
# -*- coding: utf-8 -*-
"""
@Time : 2022/10/19 9:39
@Author : JackXia
@Email : 915624876@qq.com
@QQ : 915624876
@File : 多线程.py
@Software: PyCharm
"""
import threading
sum = 0
def test1():
global sum
for i in range(1000000):
sum += 1
def test2():
global sum
for i in range(1000000):
sum -= 1
if __name__ == '__main__':
t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=test2)
t1.setDaemon(True)
t1.start()
t2.start()
print(sum) # -237479
t1.join()
t2.join()
什么时候会释放?
1. giL会根据执行的完节码行数(1000个字节码左右、根据版本差异)以及时间片(15ms)释放gil
2. 遇到io操作的时会主动释放给别的线程