【问题标题】:How to execute a class member function in a separate thread using C++11 thread class?如何使用 C++11 线程类在单独的线程中执行类成员函数?
【发布时间】:2013-03-22 00:07:38
【问题描述】:

我正在尝试使用 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。我使用的编译器是 Xcode 附带的 Apple LLVM 4.2。

上面的代码不起作用。编译器错误说"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 和线程类的新手。有人可以帮我吗?

【问题讨论】:

    标签: c++ c++11 clang xcode4.6


    【解决方案1】:

    实例应该是第二个参数,像这样:

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

    【讨论】:

    • 值得指出的是,如果他立即调用.join(),OPs 代码是没有用的。
    • 不幸的是,如果 arg2 是一个参考,这不起作用。
    • @Groosha:arg2 是一个表达式,表达式永远不是引用。但是,如果您想通过引用传递参​​数,可以将其包装在std::refstd::thread(&amp;X::f, this, std::ref(arg))
    【解决方案2】:

    我仍然对上述答案有疑问(我认为它抱怨它无法复制智能指针?),所以用 lambda 重新表述:

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

    然后它编译并运行良好。 AFAIK,这同样有效,而且我个人觉得它更具可读性。

    (注意:我也将join() 更改为detach(),正如我预期的那样。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多