我应该什么时候打电话给皮吉鲁?

2024-09-29 23:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用C编写性能感知代码,并用pythoncapi和ctypes包装functions参数。你知道吗

我对PyGILState_Ensure感到困惑。它保护什么?我应该什么时候锁定或释放GIL。你知道吗

例如:

extern "C" DLL PyObject * foo(PyObject * capsule, PyObject *pystr) {
    MyClass *pointer = PyCapsule_GetPointer(capsule, "MyClass");
    string s = convert_python_string_to_std_string(pystr);
    auto state = PyGILState_Ensure();
    try {
        vector<string> strs = a_very_computation_function(pointer, s);
        PyGILState_Release(state);
        PyObject *output = convert_std_string_to_python_string_list(strs);
        return output
    }
    catch (std::exception e) {
        PyErr_SetString(PyExc_RuntimeError, e.what());
        PyGILState_Release(state);
        return NULL;
    }
}

在python中,ctypes以如下方式包装它:

    lib = cdll.LoadLibrary("mydll.dll")
    lib.foo.argtypes = [ py_object, py_object ] #capsule, str
    lib.foo.restype = py_object # [str]

foo函数取一个类似于"abcd"的python字符串,做一些繁重的计算。 然后返回python中的字符串列表,如["123","qwer","xyz"]。你知道吗

foo函数不创建任何线程。你知道吗

因为a_very_computation_function可能需要很长时间。我应该在执行死刑的时候释放吉尔?你知道吗

PyObject读取的内容是否需要受到GIL的保护(在“确保”和“释放”范围内)?你知道吗

生成新的PyObject是否需要保护免受GIL的影响?你知道吗

调用PyErr_SetString是否需要受到GIL的保护?你知道吗

我应该在哪里添加PyGILState_EnsurePyGILState_Release?你知道吗


Tags: pyreleasestringobjectfoolibctypespyobject

热门问题