线程函数中的c++函数

c++ Function inside Thread function

本文关键字:函数 c++ 线程      更新时间:2023-10-16

我正在以以下方式创建一个boost线程。

static void* ThreadFuncCall(void *arg) { return ((TestClass*)arg)->Thread1Func((TestClass*)arg
Thread1 = new boost::thread((boost::bind(&TestClass::ThreadFuncCall, this)));
void* TestClass::Thread1Func(TestClass* testClass){
    //Accessing the member variables here
    testClass->m_active = true;
    //call another function here
}

Thread1Func内部,我想调用另一个函数,我想将TestClass的对象传递给它,就像我传递给ThreadFuncCall一样。

我想知道我们是否可以在线程函数中调用另一个函数?

如果可以的话,那么我如何将TestClass的对象传递给它呢?

是的,您可以从另一个函数调用一个函数。函数调用将在与原始函数相同的线程中执行。要将指向该类的指针传递给另一个函数,请执行与ThreadFunc1相同的操作。

void* TestClass::Thread1Func(TestClass* testClass){
    //Accessing the member variables here
    testClass->m_active = true;
    //call another function here
    int i = function1(testClass, "hello world");
}
int function1(TestClass* testClass, char* text){
    testClass->printText(text);
    return 7;
}