【发布时间】:2019-09-16 12:49:42
【问题描述】:
我正在编写一个 C++ 应用程序,我想在其中使用嵌入式 Python 3.7 同时运行多个 Python 脚本。脚本应彼此独立运行,因此它们不应共享任何变量。
我想我终于想通了。但我只是想确定这是否是正确的方法。谁能确认这段代码没有任何隐藏的问题,或者是否有更好的方法来解决问题?
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <thread>
#include <chrono>
PyThreadState *threadState;
void longRunningFunction () {
PyThreadState *t = PyEval_SaveThread();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
PyEval_RestoreThread(t);
}
void run () {
// Prepare
PyEval_RestoreThread(threadState);
PyThreadState *t = Py_NewInterpreter();
// Execute Python code
// For simplicity of the example, this is mixed with C++ code.
// Usually you would have the for loop and the call
// to longRunningFunction() in Python code.
PyRun_SimpleString("x = 0");
for (int i=0; i<5; i++) {
PyRun_SimpleString("x += 1; print(x, flush=True)");
longRunningFunction();
}
// Clean up
Py_EndInterpreter(t);
PyThreadState_Swap(threadState);
PyEval_SaveThread();
}
#define THREAD_COUNT 3
int main () {
// Initialize Python
Py_Initialize();
threadState = PyEval_SaveThread();
// Start threads
std::thread thread[THREAD_COUNT];
for (int i=0; i<THREAD_COUNT; i++) {
thread[i] = std::thread(run);
}
// Wait for threads to finish
for (int i=0; i<THREAD_COUNT; i++) {
thread[i].join();
}
// Finalize Python
Py_Finalize();
}
编译代码:
g++ main.cpp "-IC:/Program Files/Python37_64/include" "-LC:/Program Files/Python37_64/libs" -lpython37 -o main.exe
【问题讨论】:
标签: python c++ concurrency cpython python-embedding