2009-11-21 43 views
3

我有一个使用嵌入式Python解释器和Python C API的C++应用程序。它可以使用PyRun_SimpleFile和PyObject_CallMethod来评估Python文件和源代码。Python线程不能在C++应用程序嵌入式解释器中运行

现在我其中有一个工作线程,其子类threading.Thread并有一个简单的运行重新实施一个Python源代码:

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) 

的问题是,在“运行”只打印在一次控制台。

如何确保python线程与我的C++应用程序GUI循环保持并行运行。

由于提前,

保罗

+0

只是一个检查:你是如何调用你的线程? – int3 2009-11-21 14:50:51

+0

我有一个类似的问题在[这里](http://stackoverflow.com/a/30746760/1249320) – Bruce 2015-06-10 04:07:08

回答

2

我有同样类似的问题,并找到了解决办法。我知道这个线程非常老,但万一有人想知道...这是一个代码示例,它可以满足您的需求。

#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

什么是主线程在做什么?它是否只是将控制权交还给您的C++应用程序?如果是这样,请记住在主线程中没有运行任何Python代码时释放GIL(全局解释器锁),否则其他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

相关问题