codecamp

15.7 从C扩展中释放全局锁

问题

You have C extension code in that you want to execute concurrently with other threadsin the Python interpreter. To do this, you need to release and reacquire the global in‐terpreter lock (GIL).

解决方案

In C extension code, the GIL can be released and reacquired by inserting the followingmacros in the code:

include “Python.h”...

PyObject *pyfunc(PyObject *self, PyObject *args) {...Py_BEGIN_ALLOW_THREADS// Threaded C code. Must not use Python API functions...Py_END_ALLOW_THREADS...return result;
}

讨论

The GIL can only safely be released if you can guarantee that no Python C API functionswill be executed in the C code. Typical examples where the GIL might be released arein computationally intensive code that performs calculations on C arrays (e.g., in ex‐tensions such as numpy) or in code where blocking I/O operations are going to be per‐formed (e.g., reading or writing on a file descriptor).While the GIL is released, other Python threads are allowed to execute in the interpreter.The Py_END_ALLOW_THREADS macro blocks execution until the calling threads reacquiresthe GIL in the interpreter.

15.6 从C语言中调用Python代码
15.8 C和Python中的线程混用
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }