将 Python 嵌入到 C++ 分段错误

Embedding Python to C++ Segmentation fault

我正在尝试使用 C++ 线程跟踪 python 脚本的执行(如果有人知道更好的方法,请随时提及)

这是我目前的代码。

#define PY_SSIZE_T_CLEAN
#include </usr/include/python3.8/Python.h>
#include <iostream>
#include <thread>

void launchScript(const char *filename){
    Py_Initialize();
    FILE *fd = fopen(filename, "r");
    PyRun_SimpleFile(fd, filename);
    PyErr_Print();
    Py_Finalize();
 

}
int main(int argc, char const *argv[])
{
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append(\".\")");
    std::thread first (launchScript,"script.py");
    std::cout << "Thread 1 is running with thread ID: " << first.get_id() << std::endl;
    std::thread second (launchScript,"script2.py");
    std::cout << "Thread 2 is running with thread ID: " << second.get_id() << std::endl;
   
    first.join();
    second.join();
    Py_Finalize();
    return 0; 
   
}

Script.py 只是有一个打印语句,打印“Hello World” Script2.py 有一个打印语句,打印“再见世界”

我使用以下命令构建应用程序

g++ -pthread -I/usr/include/python3.8/ main.cpp -L/usr/lib/python3.8/config-3.8-x86_64 linux-gnu -lpython3.8 -o output

当我 运行 ./output 时,我在终端上收到以下内容

Thread 1 is running with thread ID: 140594340370176
Thread 2 is running with thread ID: 140594331977472
GoodBye World
./build.sh: line 2:  7864 Segmentation fault      (core dumped) ./output

我想知道为什么会出现分段错误。我尝试使用 PyErr_Print(); 进行调试但这并没有给我任何线索。

欢迎任何反馈。

在对程序进行大约 20 分钟的测试和调试后,我发现 问题是 引起的,因为在您的示例中您创建了第二个 std::thread 名为 secondfirst 线程上调用 join() 之前。

因此,要解决,只需确保您在创建 second 线程之前使用了 first.join(),如下所示:

int main(int argc, char const *argv[])
{
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append(\".\")");
    std::thread first (launchScript,"script.py");
    std::cout << "Thread 1 is running with thread ID: " << first.get_id() << std::endl;
//--vvvvvvvvvvvvv-------->call join on first thread before creating the second std::thread
    first.join();
    
    std::thread second (launchScript,"script2.py");
    std::cout << "Thread 2 is running with thread ID: " << second.get_id() << std::endl;
   
    second.join();
 
    Py_Finalize();
    return 0; 
   
}