2016-11-15 62 views
0

我有一個使用boost python的C++類。我正在嘗試使用pthread從C++的線程運行python代碼。問題是下面的代碼沒有產生任何輸出。我期待stdout輸出John DOE。看起來&this->instance不包含在對象內部設置的值。如何將當前對象或其實例變量傳遞給pthread_create,以便pthread能夠看到正在傳遞的內容?pthread沒有看到作爲參數傳遞的實例變量

Python:

class A: 
    def __init__(self, name): 
     self.name = name 

    def printName(self, lastName): 
     print self.name + " " + lastName 

C++:

#include <boost/python.hpp> 
#include <string.h> 
#include <pthread.h> 

using namespace std; 
using namespace boost::python; 

class B { 
    public: 
     object instance; 
     B(); 
     void setupPython(); 
     static void *runPython(void *); 
}; 

B::B() { 
    Py_Initialize(); 
} 

void B::setupPython() { 
    pthread_t t1; 
    try { 
     object a = import("A"); 
     instance = a.attr("A")("John"); 
     pthread_create(&t1, NULL, runPython, &this->instance); // THIS IS PROBLEM 
    } 
    catch(error_already_set const &) { 
     PyErr_Print(); 
    } 
} 

void *B::runPython(void *instance) { 
    ((object *)instance)->attr("printName")("DOE"); 
} 

int main() { 
    B b; 
    b.setupPython(); 
} 

謝謝。

回答

1

的問題是:

int main() { 
    B b; 
    b.setupPython(); // You create a thread here 
    // But here, b is destroyed when it's scope ends 
} 

在你的線程的代碼不能保證b運行之前被釋放。

嘗試在堆中分配B和檢查是否正常工作:

int main() { 
    B* b = new B(); 
    b->setupPython(); 
    // also, you should add a call to pthread_join 
    // here to wait for your thread to finish execution. 
    // For example, changing setupPython() to return the 
    // pthread_t handle it creates, and calling pthread_join on it. 
} 
+0

*嘗試在堆中分配B和檢查是否正常工作:*仍可能會無法正常工作 - 當'main()的返回' ,程序結束。 –

+0

@AndrewHenle正確,編輯答案。 – Steeve

+0

@Steeve謝謝你的回答。有用。 – pseudo