![](/img/trans.png)
[英]error assigning a function pointer passed as an argument in the constructor to a private instance variable
[英]pthread does not see instance variable passed as argument
我在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();
}
謝謝。
問題是:
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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.