pthread没有看到作为参数传递的实例变量

时间:2016-11-15 18:36:37

标签: c++ reference pthreads pthread-key-create

我在C ++中有一个使用boost python的类。我试图使用pthread在C ++的线程中运行python代码。问题是下面的代码不会产生任何输出。我期待stdout中的输出John DOE。似乎&this->instance没有携带在对象内设置的值。如何将当前对象或其实例变量传递给pthread_create,以便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 个答案:

答案 0 :(得分: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.
}