【问题标题】:Force the GIL not to switch threads强制 GIL 不切换线程
【发布时间】:2012-12-22 03:00:25
【问题描述】:

我正在分析一些多线程 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()

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

【问题讨论】:

    标签: python multithreading profiling gil


    【解决方案1】:

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

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

    每当您调用sys.setcheckinterval(count) 时,当前的“计数器”都会重置为新值,因此一旦您调用它,至少count 字节码指令都不允许线程切换。

    【讨论】:

    • 查看我的问题更新。通过sys.setcheckinterval()make_the_interpreter_not_change_thread() 中放置大量数字会起作用吗?解释器是否更改了当前 python 虚拟指令的计数,或者新值是否仅在解释器检查的下一个周期生效,这很不幸在code_to_profile() 期间发生?
    • @Jonathan:该函数在调用时会重置当前计数。因此,使用较大的值调用它可以保证不会针对该数量的字节码指令进行线程切换。
    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多