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
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With