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
-
just a check: how are you invoking your thread?int3– int32009年11月21日 14:50:51 +00:00Commented Nov 21, 2009 at 14:50
-
I have an answer to similar question at hereBruce– Bruce2015年06月10日 04:07:08 +00:00Commented Jun 10, 2015 at 4:07
3 Answers 3
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;
}
1 Comment
What is the main thread doing? Is it simply returning control to your C++ app? If so, remember to release the GIL (Global Interpreter Lock) when not running any Python code in your main thread, otherwise your other Python threads will stall waiting for the GIL to be released.
The easiest way to do so is to use the Py_BEGIN_ALLOW_THREADS / Py_END_ALLOW_THREADS macros.
See the doc at: http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock
Comments
Though this thread is old, I think my answer might be helpful for some others who meet the same problem.
I ran into the same problem two days ago, I googled, and found this thread, but no luck with @Reuille's solution.
Now I'd like to share a workaround I found just now: you have to run
app.exec()
in your Python scripts instead of your C++ main function. It's a weird bug.
edit: you could see the details of my fix on my project.