前言:
-
C python global interpreter lock has GIL
-
The impact of the use of multi-threading performance
test 4 核的 window电脑
import time
def time_need(func):
def inner(*args, **kwargs):
start = time.time()
ret = func(*args, **kwargs)
stop = time.time()
print(stop - start)
return ret
return inner
@time_need
def countdown(n):
while n > 0:
n -= 1
if __name__ == '__main__':
COUNT = 100000000
countdown(COUNT)
时间 4.45 平均
import time
from threading import Thread
def time_need(func):
def inner(*args, **kwargs):
start = time.time()
ret = func(*args, **kwargs)
stop = time.time()
print(stop - start)
return ret
return inner
@time_need
def countdown(n):
while n > 0:
n -= 1
if __name__ == '__main__':
COUNT = 100000000
大专栏 python中的线程与GILs="n">t1 = Thread(target=countdown, args=(COUNT//2,))
t2 = Thread(target=countdown, args=(COUNT//2,))
t1.start();t2.start()
t1.join();t2.join()
time 15.05
python thread
-
System-level threads
• Python threads are real system threads • POSIX threads (pthreads) • Windows threads
-
The main thread control
• Fully managed by the host operating system
-
It represents the Python interpreter threaded execution process (is written in C)
• Represent threaded execution of the Python interpreter process (written in C)
You can not be executed in parallel
GIL interpreter so that only one thread running
• When a thread is running, it holds the GIL
• GIL released on I/O (read,write,send,recv,etc.)
CPU bound compute-intensive tasks
CPU密集型的线程
(Not execute IO operations) are treated specially
Periodically checks
per check every 100 ticks
通过设置 sys.setcheckinterval() 可以修改周期
ticks 不是时间概念,它对应着python解释器的指令
Currently running thread will execute a periodic motion:
• Resets the tick counter 重置tick counter
• Runs signal handlers if the main thread 主线程会运行 signal handler
• Releases the GIL 释放GIL锁
• Reacquires the GIL 获取GIL锁
GIL and principles thread switch
(1) python lock
python interpreter provides only one type of lock (in C language), constructed to achieve 线程同步的原型
不是简单的互斥锁
It is a binary structure 二进制信号量 pthreads互斥锁
and条件变量
Lock structure:
locked = 0 # Lock status
mutex = pthreads_mutex() # Lock for the status
cond = pthreads_cond() # Used for waiting/wakeup
Operating mode:
(2) the thread switch