Python threads not starting in C ++ Application Embedded Interpreter

I have a C ++ application that uses the built-in python interpreter with the Python C API. It can evaluate Python files and source code using PyRun_SimpleFile and PyObject_CallMethod.

Now I have the python source code that has a processed thread that subclasses threading.Thread and has a simple re-implementation of the run:

import time
from threading import Thread
class MyThread(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        while True:
            print "running..."
            time.sleep(0.2)

The problem is that the “run” is printed only once in the console.

How can I make sure that python threads continue to work in parallel with my C ++ application GUI circuit.

Thanks in advance,

Floor

+3
source share
2 answers

. , , - ... , , .

#include <Python.h>

#include <iostream>
#include <string>
#include <chrono>
#include <thread>

int main()
{
    std::string script =
        "import time, threading                        \n"
        "" 
        "def job():                                    \n"
        "    while True:                               \n"
        "         print('Python')                      \n"
        "         time.sleep(1)                        \n"
        ""
        "t = threading.Thread(target=job, args = ())   \n"
        "t.daemon = True                               \n"
        "t.start()                                     \n";

    PyEval_InitThreads();
    Py_Initialize();

    PyRun_SimpleString(script.c_str());

    Py_BEGIN_ALLOW_THREADS

    while(true)
    {
        std::cout << "C++" << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }

    Py_END_ALLOW_THREADS

    Py_Finalize();

    return 0;
}
+2

? ++-? , GIL (Global Interpreter Lock), - Python , Python GIL.

- Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS.

. http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock

+2

Source: https://habr.com/ru/post/1723545/


All Articles