I am trying to track the execution of python scripts with C++ Threads (If anyone knows a better approach, feel free to mention it)
This is the code I have so far.
#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 just has a print statement that prints "Hello World" Script2.py has a print statement that prints "Goodbye World"
I build the application with the following commands
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
When I run ./output, I receive the following on my terminal
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
I am wondering why I am getting Segmentation Fault. I have tried to debug with PyErr_Print(); but that has not given me any clues.
Any feed back is appreciated.
Py_InitializeandPy_Finalizemultiple timesPy_InitializeandPy_Finalizefrom the function, but It is still inconsistent, sometimes it gives me the segmentation fault error, sometimes both scripts run successfully with no segmentation fault, sometimes only one script runs successfully.