使用同一个类中的函数在类中创建线程

use*_*501 16 c++ multithreading c++11

我希望能够定义一个包含一些数据成员的类,以及一个可以访问那些私有数据成员的函数.

然后我想要一个公共函数,它创建一些线程,它们对类的数据成员进行操作.我在编译代码时遇到了一些麻烦.

不要担心互斥或数据保护,这不会成为问题,因为这只是一些用于测试的示例代码.

class foo {
    public:
    void make_foo_func_threads();

    private:
    void foo_func();

    char private_data;
    std::vector<std::thread> some_threads;
}

void foo::foo_func() {
    while(1) {
        private_data = 'A';
    }
}

void foo::make_foo_func_thread() {
    for(...) some_threads.push_back(std::thread(foo_func));
    for(...) some_threads.join();
}
Run Code Online (Sandbox Code Playgroud)

编译器给我错误:

'没有匹配调用std :: thread :: thread()'

显然有"用于从参数1没有已知的转换<unresolved overloaded function type>void (foo::*&&)'.

嗯,是的,我不知道这意味着什么除了编译器在理解如何解决foo_func方面有困难 - 我想.

我如何帮助编译器理解我想要做什么,所以它不会再困扰我了.毫无疑问,我写的代码是不合法的,如果是这样,有人可以解释为什么对我来说就是这种情况.谢谢!

hmj*_*mjd 23

foo_func是一个(非static)成员函数,它需要一个foo操作的实例.必须将此实例提供给线程构造函数.如果您参考std :: thread :: thread参考页面,它会解释在新线程中执行的代码.相关点是指f成员函数的指针:

  • 如果f是指向类的成员函数的指针T,则调用它.返回值被忽略.实际上,执行以下代码:
    • (t1.*f)(t2, ..., tN)如果类型t1是从T,T派生或引用的类型T.
    • ((*t1).*f)(t2, ..., tN) 除此以外.

所以很明显,实例是必需的.

改成:

for(...) some_threads.push_back(std::thread(&foo::foo_func, this));
Run Code Online (Sandbox Code Playgroud)

简单的例子:

#include <iostream>
#include <thread>
#include <vector>

class foo
{
public:
    void make_foo_func_threads()
    {
        for (int i = 0; i < 5; ++i)
            some_threads.push_back(std::thread(&foo::foo_func, this));
        for (auto& t: some_threads) t.join();
    }

private:
    void foo_func() { std::cout << "Hello\n"; }
    std::vector<std::thread> some_threads;
};

int main()
{
    foo f;
    f.make_foo_func_threads();
}
Run Code Online (Sandbox Code Playgroud)

  • 糟糕,没有我的坏我没有把f.make_foo_func_threads(); 在主!对不起,它适用于所有人不要恐慌!> < (2认同)