C++11 thread调用对象的成员函数

发布于 2022-09-04 22:20:05 字数 150 浏览 29 评论 0

如果掉一个类的成员函数,大概是这样。

clientThread = std::thread(&Client::sendMessage,“message”);

但如果希望这个类的特定对象,执行这个操作,怎么处理?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

好多鱼好多余 2022-09-11 22:20:05

std::thread 调用类的成员函数需要传递类的一个对象作为参数:

#include <thread>
#include <iostream>

class bar {
public:
  void foo() {
    std::cout << "hello from member function" << std::endl;
  }
};

int main()
{
  std::thread t(&bar::foo, bar());
  t.join();
}

如果是在类的成员函数中处理thread,传入 this 即可,如:

std::thread spawn() {
    return std::thread(&blub::test, this);
  }

参考:stackoverflow

心房敞 2022-09-11 22:20:05

参考C plus plus

Parameters
fn
A pointer to function, pointer to member, or any kind of move-constructible function object (i.e., an object whose class
defines operator(), including closures and function objects). The
return value (if any) is ignored.
args...
Arguments passed to the call to fn (if any). Their types shall be move-constructible. If fn is a member pointer, the first argument shall be an object for which that member is defined or a reference, or a pointer to it).
x
thread object whose state is moved to the constructed object.

// constructing threads
#include <iostream>       // std::cout
#include <atomic>         // std::atomic
#include <thread>         // std::thread
#include <vector>         // std::vector

std::atomic<int> global_counter (0);

void increase_global (int n) { for (int i=0; i<n; ++i) ++global_counter; }

void increase_reference (std::atomic<int>& variable, int n) { for (int i=0; i<n; ++i) ++variable; }

struct C : std::atomic<int> {
  C() : std::atomic<int>(0) {}
  void increase_member (int n) { for (int i=0; i<n; ++i) fetch_add(1); }
};

int main ()
{
  std::vector<std::thread> threads;

  std::cout << "increase global counter with 10 threads...\n";
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(increase_global,1000));

  std::cout << "increase counter (foo) with 10 threads using reference...\n";
  std::atomic<int> foo(0);
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(increase_reference,std::ref(foo),1000));

  std::cout << "increase counter (bar) with 10 threads using member...\n";
  C bar;
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(&C::increase_member,std::ref(bar),1000));

  std::cout << "synchronizing all threads...\n";
  for (auto& th : threads) th.join();

  std::cout << "global_counter: " << global_counter << '\n';
  std::cout << "foo: " << foo << '\n';
  std::cout << "bar: " << bar << '\n';

  return 0;
}

类似这样 std::thread(&C::increase_member,std::ref(bar),1000)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文