我正在用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_Ensure
和PyGILState_Release
?你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐