-->

如何使用C ++ 11线程类在单独的线程执行的一类的成员函数?(How to execute a c

2019-08-18 10:46发布

我想用C ++ 11的std::thread类运行类的成员函数并行执行。

头文件的代码类似于:

class SomeClass {
    vector<int> classVector;
    void threadFunction(bool arg1, bool arg2);
public:
    void otherFunction();
};

cpp文件是类似于:

void SomeClass::threadFunction(bool arg1, bool arg2) {
    //thread task
}

void SomeClass::otherFunction() {
    thread t1(&SomeClass::threadFunction, arg1, arg2, *this);
    t1.join();
}

我使用在Mac OS X 10.8.3的Xcode 4.6.1。 我使用的编译器是苹果LLVM 4.2,其附带的Xcode的。

上面的代码不起作用。 编译器错误说, "Attempted to use deleted function"

在线程创建的线则显示以下按摩。

In instantiation of function template specialization 'std::__1::thread::thread<void (SomeClass::*)(bool, bool), bool &, bool &, FETD2DSolver &, void>' requested here

我在C ++ 11线程类是新的。 可能有人帮助我吗?

Answer 1:

实例应该是第二个参数,如下所示:

std::thread t1(&SomeClass::threadFunction, *this, arg1, arg2);


Answer 2:

我仍然有与上述答案(我认为这是抱怨它无法在智能指针复制?)的问题,所以用一个lambda改写它:

void SomeClass::otherFunction() {
  thread t1([this,arg1,arg2](){ threadFunction(arg1,arg2); });
  t1.detach();
}

然后编译并运行良好。 据我所知,这是一样高效,我个人认为它更具有可读性。

(注:我也改变了join()detach()如我所料,这是意图。)



文章来源: How to execute a class member function in a separate thread using C++11 thread class?