注意成员函数以及【operator()】的使用 std::ref 关键字 noexcept :告诉编译器函数不会出现异常

  1. #include <iostream>
  2. #include <utility>
  3. #include <thread>
  4. #include <chrono>
  5. void f1(int n)
  6. {
  7. for (int i = 0; i < 5; ++i) {
  8. std::cout << "Thread 1 executing\n";
  9. ++n;
  10. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11. }
  12. }
  13. void f2(int& n)
  14. {
  15. for (int i = 0; i < 5; ++i) {
  16. std::cout << "Thread 2 executing\n";
  17. ++n;
  18. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19. }
  20. }
  21. class foo
  22. {
  23. public:
  24. void bar()
  25. {
  26. for (int i = 0; i < 5; ++i) {
  27. std::cout << "Thread 3 executing\n";
  28. ++n;
  29. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  30. }
  31. }
  32. int n = 0;
  33. };
  34. class baz
  35. {
  36. public:
  37. void operator()()
  38. {
  39. for (int i = 0; i < 5; ++i) {
  40. std::cout << "Thread 4 executing\n";
  41. ++n;
  42. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  43. }
  44. }
  45. int n = 0;
  46. };
  47. int main()
  48. {
  49. int n = 0;
  50. foo f;
  51. baz b;
  52. std::thread t1; // t1 is not a thread
  53. std::thread t2(f1, n + 1); // pass by value
  54. std::thread t3(f2, std::ref(n)); // pass by reference
  55. std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
  56. std::thread t5(&foo::bar, &f); // t5 runs foo::bar() on object f
  57. std::thread t6(b); // t6 runs baz::operator() on a copy of object b
  58. t2.join();
  59. t4.join();
  60. t5.join();
  61. t6.join();
  62. std::cout << "Final value of n is " << n << '\n';
  63. std::cout << "Final value of f.n (foo::n) is " << f.n << '\n';
  64. std::cout << "Final value of b.n (baz::n) is " << b.n << '\n';
  65. }

std::ref

std::ref 与 std::cref区别:
c代表const,即传 const 引用,只读!

  1. #include <functional>
  2. #include <iostream>
  3. void f(int& n1, int& n2, const int& n3)
  4. {
  5. std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
  6. ++n1; // increments the copy of n1 stored in the function object
  7. ++n2; // increments the main()'s n2
  8. // ++n3; // compile error
  9. }
  10. int main()
  11. {
  12. int n1 = 1, n2 = 2, n3 = 3;
  13. std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));
  14. n1 = 10;
  15. n2 = 11;
  16. n3 = 12;
  17. std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
  18. bound_f();
  19. std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
  20. }
  21. Before function: 10 11 12
  22. In function: 1 11 12
  23. After function: 10 12 12