15.7 從C擴(kuò)展中釋放全局鎖

2018-02-24 15:27 更新

問(wèn)題

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.

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)