强制GIL不要切换线程

时间:2013-01-08 09:32:46

标签: python multithreading profiling gil

我正在分析一些多线程CPython代码 为了衡量执行特定代码段所需的时间,我想强制GIL (Global Interpreter Lock) 而不是在该段的线程之间切换。怎么办呢?

更新
假设以下伪代码:

some_code_1()
make_the_interpreter_not_change_thread()
take_start_time()   # time critical
code_to_profile()   # time critical
take_end_time()     # time critical
release_the_interpreter()
some_code_2()

我担心的是,解释器会在“时间关键”分析期间切换线程。

1 个答案:

答案 0 :(得分:6)

GIL不会切换线程。 GIL是一个互斥锁,可以防止多个线程同时执行字节码。因此,为了防止线程切换,您需要查看其他地方。

您可以使用非常大的值调用sys.setcheckinterval(),以防止在分析代码时进行切换。

每当您调用sys.setcheckinterval(count)时,当前的'计数器'都会重置为新值,因此只要您调用它,就不会允许至少count个字节码指令进行线程切换。