我正在嘗試使用 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(); 進行除錯 但這并沒有給我任何線索。
任何反饋表示贊賞。
uj5u.com熱心網友回復:
在測驗和除錯程式大約 20 分鐘后,我發現問題是由于在您的示例中您在呼叫執行緒之前創建了第二個std::thread命名的。secondjoin()first
因此,要解決這個問題,只需確保您first.join()在創建second執行緒之前使用過,如下所示:
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481900.html
