【问题标题】:How to initiate a std::thread calling a function that expects a function as a parameter?如何启动一个 std::thread 调用一个期望函数作为参数的函数?
【发布时间】:2016-07-25 12:42:51
【问题描述】:

我有一个希望在 std::thread 中运行的类成员函数,它需要一个函数作为参数,如下所示:

ModbusAgent::poolingThread(int position, std::function<int(int, uint16_t*)> readFunction)

所以问题是:如何实例化一个 std::thread 来调用它?

【问题讨论】:

  • 你不觉得你自己提出和回答的这个问题最适合SO Documentation吗?
  • 函数参数有什么特别之处?这只是另一个参数。
  • 使用 lambda 会容易得多

标签: c++ multithreading c++11 stl


【解决方案1】:

所以这是我找到的方法:

class A {
public:
    int bar(int, uint16_t*) { return 0; }

    void foo(int position, std::function<int(int, uint16_t*)> readFunction) {
            readFunction(position, nullptr);
    }

    void b() {
        std::function<int(int, uint16_t*)> readFunction = std::bind(&A::bar, *this, std::placeholders::_1, std::placeholders::_2);
        std::thread(&A::foo, this, 5, readFunction);
    }
};


int main() {
    A a;
    a.b();
}

【讨论】:

    猜你喜欢
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 2021-02-14
    • 2018-11-13
    • 2020-03-09
    • 1970-01-01
    相关资源
    最近更新 更多