gpt4 book ai didi

c++ - 使用同一类的函数在类内创建线程

转载 作者:IT老高 更新时间:2023-10-28 22:36:48 25 4
gpt4 key购买 nike

我希望能够定义一个包含一些数据成员的类,以及一个可以访问这些数据成员的函数,这些数据成员是私有(private)的。

然后我想要一个公共(public)函数,它创建一些线程,这些线程对类的数据成员进行操作。我在编译我的代码时遇到了一些问题。

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

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();
}

编译器给了我错误:

'no matching call to std::thread::thread()'

显然,对于来自 <unresolved overloaded function type> 的参数 1 没有已知的转换。至void (foo::*&&)' .

呃,是的,我不知道这意味着什么,除了编译器无法理解如何解析 foo_func - 我想。

我怎样才能帮助编译器了解我想要做什么,这样它就不会再因为任何错误而困扰我了。毫无疑问,我编写的代码是不合法的,如果是这样的话,有人可以向我解释为什么会这样。谢谢!

最佳答案

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

  • If f is pointer to a member function of class T, then it is called. The return value is ignored. Effectively, the following code is executed:
    • (t1.*f)(t2, ..., tN) if the type of t1 is either T, reference to T or reference to type derived from T.
    • ((*t1).*f)(t2, ..., tN) otherwise.

所以很明显该实例是必需的。

改为:

for(...) some_threads.push_back(std::thread(&foo::foo_func, this));

Simple example :

#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();
}

关于c++ - 使用同一类的函数在类内创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17472827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com