我已将Python3嵌入到我的大型C++应用程序中。Python为用户提供了自定义数据处理的脚本功能。
问题:我有许多与Python交互的线程,但我不知道如何使用GIL来保护我的代码。到目前为止,我唯一使我的代码工作的方法是使用
这里有一个非常简化的示例,重现了我的问题:
boost::mutex
。这里有一个非常简化的示例,重现了我的问题:
- 线程A首先调用
Init()
来初始化Python(静态函数)。 - 线程B调用
Pythonize()
在Python上执行一些操作。线程B在第一次尝试锁定GIL时被阻塞。
#include <iostream>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include "Python.h"
struct RTMaps_GILLock
{
RTMaps_GILLock()
{
std::cout << "Locking..." << std::endl;
m_state = PyGILState_Ensure();
}
~RTMaps_GILLock()
{
std::cout << "Unlocking..." << std::endl;
PyGILState_Release(m_state);
}
private:
PyGILState_STATE m_state;
};
#define GILLOCK RTMaps_GILLock lock;
class PythonEmbed
{
public:
static void Init()
{
Py_Initialize();
// EDIT : adding those two lines made my day :
PyEval_InitThreads(); // This acquires GIL
PyEval_SaveThread(); // Release the GIL
}
void Pythonize()
{
GILLOCK;
// Never goes here :(
std::cout << "OK" << std::endl;
}
};
int main()
{
PythonEmbed::Init();
PythonEmbed pyt;
boost::thread t(boost::bind(&PythonEmbed::Pythonize, pyt));
t.join();
}
在第一个锁调用中出现死锁。控制台显示: 正在锁定...
“OK”从未被打印。我做错了什么?
编辑:已更正代码,现在它可以工作了。我需要从主线程释放GIL。