【问题标题】:Multithreaded embedded Python. Is this right?多线程嵌入式 Python。这是正确的吗?
【发布时间】: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


    【解决方案1】:

    在另一个进程中运行 Python 脚本更简单、更安全且性能更高(在多个 Python 线程的情况下)。由于全局解释器锁定,您的 Python 线程不能在一个进程内并行运行。这样也更容易中断和终止那些 Python 进程,而不会弄乱你的进程。

    【讨论】:

    • 在我的情况下,脚本需要与流程的其他部分进行通信。所以我可以在不同的进程中运行脚本,但是我必须发明一些通信协议,它不会再简单了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多