0

ブースト python を使用する C++ のクラスがあります。pthread を使用して C++ からスレッドで Python コードを実行しようとしています。問題は、以下のコードが出力を生成しないことです。John DOEstdout での出力を期待していました。&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();
}

ありがとうございました。

4

1 に答える 1

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.
}
于 2016-11-16T12:10:06.073 に答える