Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Threads do not run in C++ Application Embedded Interpreter

I have a C++ application which uses embedded python interpreter with the Python C API. It can evaluate Python files and source code with PyRun_SimpleFile and PyObject_CallMethod.

Now I have a python source code which has a worked thread which subclasses threading.Thread and has a simple run re-implementation:

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 "running" is printed only once in the console.

How can I make sure that python threads keep on running parallel to my C++ applications GUI loop.

Thanks in advance,

Paul

like image 778
Paul Avatar asked Nov 21 '09 14:11

Paul


People also ask

Why threading is not possible in Python?

Python doesn't support multi-threading because Python on the Cpython interpreter does not support true multi-core execution via multithreading. However, Python does have a threading library.

How are Python threads executed?

The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock. The acquire(blocking) method of the new lock object is used to force threads to run synchronously.

How do I enable threads in Python?

You need to assign the thread object to a variable and then start it using that varaible: thread1=threading. Thread(target=f) followed by thread1. start() . Then you can do thread1.

How do you communicate between Python threads?

Perhaps the safest way to send data from one thread to another is to use a Queue from the queue library. To do this, create a Queue instance that is shared by the threads. Threads then use put() or get() operations to add or remove items from the queue as shown in the code given below.


1 Answers

I've had the same similar problem and found the solution. I know the thread is pretty old but just in case anybody is wondering... Here is a code sample that does what you need.

#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;
}
like image 158
Thibault Reuille Avatar answered Oct 02 '22 07:10

Thibault Reuille