当我从一个不同的C线程调用C-API的Py_Finalize()时,我得到一个错误输出,而不是我进行python调用。
我看到的错误是:
Exception ignored in: <module 'threading' from 'C:\\Python34-32\\Lib\\threading.py'>
Traceback (most recent call last):
File "C:\Python34-32\Lib\threading.py", line 1289, in _shutdown
assert tlock.locked()
AssertionError:
这只发生在Python 3.X(用3.4.2测试)中,在Python 2.7中完全相同的代码没有任何问题。
这是一个最小的例子,它显示了在使用C线程时它发生的情况,但是当一切c线程上发生了所有事情时都没有:
#include <iostream>
#include <fstream>
#include <thread>
#include <cassert>
#include <Python.h>
void make_file()
{
std::fstream file("my_test.py", std::ios::out);
file <<
"import threading\n" <<
"def my_function():\n" <<
" pass\n" ;
file.close();
}
void exec()
{
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject* pdict = PyDict_New();
PyDict_SetItemString(pdict, "__builtins__", PyEval_GetBuiltins());
PyRun_String("import my_test", Py_file_input, pdict, pdict);
PyRun_String("my_test.my_function()", Py_file_input, pdict, pdict);
assert(!PyErr_Occurred());
PyGILState_Release(gstate);
}
void basic()
{
std::cout << "--Starting Basic--" << std::endl;
Py_Initialize();
PyEval_InitThreads();
PyThreadState* threadState = PyEval_SaveThread();
exec();
PyEval_RestoreThread(threadState);
Py_Finalize();
std::cout << "--Basic Complete--" << std::endl;
}
void with_thread()
{
std::cout << "--Starting With Thread--" << std::endl;
Py_Initialize();
PyEval_InitThreads();
PyThreadState* threadState = PyEval_SaveThread();
std::thread t(exec);
t.join();
PyEval_RestoreThread(threadState);
Py_Finalize();
std::cout << "--With Thread Complete--" << std::endl;
}
int main(int argc, char* argv[])
{
make_file();
basic();
with_thread();
return 0;
}
--Starting Basic--
--Basic Complete--
--Starting With Thread--
Exception ignored in: <module 'threading' from 'C:\\Python34-32\\Lib\\threading.py'>
Traceback (most recent call last):
File "C:\Python34-32\Lib\threading.py", line 1289, in _shutdown
assert tlock.locked()
AssertionError:
--With Thread Complete--
main中的basic()/ with_thread()调用的顺序无关紧要,我甚至可以多次包含这些行而没有任何影响,每个with_thread()调用结果都在错误输出中。
使threadState成为全局,然后将exec更改为:
void exec()
{
//PyGILState_STATE gstate = PyGILState_Ensure();
PyEval_RestoreThread(threadState);
PyObject* pdict = PyDict_New();
PyDict_SetItemString(pdict, "__builtins__", PyEval_GetBuiltins());
PyRun_String("import my_test", Py_file_input, pdict, pdict);
PyRun_String("my_test.my_function()", Py_file_input, pdict, pdict);
assert(!PyErr_Occurred());
//PyGILState_Release(gstate);
threadState = PyEval_SaveThread();
}
导致错误消失,但是我有一个全局值,我需要在我的库的用户之间进行协调(在我的实际代码中,exec()函数可以由任何人编写,我有更多的初始化我跑的东西)。在保持线程兼容性的同时,有关如何使GIL像原始示例一样更加孤立的任何见解?
答案 0 :(得分:2)
尝试添加
Py_DECREF(PyImport_ImportModule("threading"));
后
PyEval_InitThreads();