前言:
-
CパイソングローバルインタプリタロックはGILを持っています
-
マルチスレッドのパフォーマンスの使用の影響
テスト 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のスレッド
-
システムレベルのスレッド
• Python threads are real system threads • POSIX threads (pthreads) • Windows threads
-
メインスレッド制御
• Fully managed by the host operating system
-
これは、Pythonインタプリタスレッド実行処理(Cで書かれている)を表します
• Represent threaded execution of the Python interpreter process (written in C)
あなたは、並列に実行することができません
GILインタプリタ一つだけのスレッドが実行するように
• When a thread is running, it holds the GIL
• GIL released on I/O (read,write,send,recv,etc.)
CPUバウンドの計算集約型のタスク
CPU密集型的线程
特別扱いされている(IOオペレーションを実行しません)
定期的にチェック
per check every 100 ticks
通过设置 sys.setcheckinterval() 可以修改周期
ticks 不是时间概念,它对应着python解释器的指令
現在実行中のスレッドは、定期的な運動を実行します:
• Resets the tick counter 重置tick counter
• Runs signal handlers if the main thread 主线程会运行 signal handler
• Releases the GIL 释放GIL锁
• Reacquires the GIL 获取GIL锁
GILと原則スレッドの切り替え
(1)Pythonのロック
Pythonインタプリタは、達成するために構成され、(C言語における)ロックの一種類のみを提供します 线程同步的原型
不是简单的互斥锁
これは、バイナリ構造であり、二进制信号量 pthreads互斥锁
かつ条件变量
ロック構造:
locked = 0 # Lock status
mutex = pthreads_mutex() # Lock for the status
cond = pthreads_cond() # Used for waiting/wakeup
作業モード:
(2)スレッドスイッチ