繁体   English   中英

将 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 有一个打印语句,打印“Goodbye World”

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

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 分钟后,我发现问题是由于在您的示例中您在first线程上调用join()之前创建了第二个名为secondstd::thread thread 。

因此,要解决这个问题,只需确保您在创建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; 
   
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM