2009-11-21 105 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

相關問題