当前位置:   article > 正文

C++11 std::async 结合 lambda, std::function<>的例子_std::async lamda

std::async lamda

下面是一个例子,编译通过。

  1. #include <future>
  2. #include <functional>
  3. #include <iostream>
  4. #include <thread>
  5. #include <chrono>
  6. using namespace std;
  7. class Msg {
  8. public:
  9. Msg(std::string name, uint32_t id) : m_name(name), m_id(id)
  10. {
  11. }
  12. virtual ~Msg()
  13. {
  14. }
  15. std::string GetName()
  16. {
  17. return m_name;
  18. }
  19. uint32_t GetId()
  20. {
  21. return m_id;
  22. }
  23. private:
  24. std::string m_name;
  25. uint32_t m_id;
  26. };
  27. void PrintInfo(Msg *msg)
  28. {
  29. for (int i = 0; i < 10; i++) {
  30. std::cout << msg->GetName() << msg->GetId() << std::endl;
  31. }
  32. }
  33. // function object point to the method.
  34. std::function<void(Msg *msg)> printFunc = PrintInfo;
  35. int main()
  36. {
  37. Msg *msg = new Msg("Hello", 999);
  38. std::future<void> fut = std::async(std::launch::async, PrintInfo, msg);
  39. Msg *msg2 = new Msg("World", 123);
  40. std::future<void> fut2 = std::async(std::launch::deferred, PrintInfo, msg2);
  41. // independent of platform.
  42. std::this_thread::sleep_for(std::chrono::milliseconds(10000));
  43. fut2.get();
  44. // use lambda
  45. std::future<bool> fut3 = std::async(std::launch::deferred, [](std::string name) -> bool {
  46. if (name == "s") {
  47. std::cout << "start!" << std::endl;
  48. return true;
  49. }
  50. return false;
  51. }, "s");
  52. std::this_thread::sleep_for(std::chrono::milliseconds(3000));
  53. fut3.get();
  54. // use function.
  55. std::future<void> fut4 = std::async(std::launch::deferred, printFunc, new Msg("Function Msg", 777));
  56. std::this_thread::sleep_for(std::chrono::milliseconds(3000));
  57. fut4.get();
  58. return 0;
  59. }

编译时记得要加上-lpthread

g++ -o test_future test_future -lpthread

输出结果

  1. Hello999
  2. Hello999
  3. Hello999
  4. Hello999
  5. Hello999
  6. Hello999
  7. Hello999
  8. Hello999
  9. Hello999
  10. Hello999
  11. World123
  12. World123
  13. World123
  14. World123
  15. World123
  16. World123
  17. World123
  18. World123
  19. World123
  20. World123
  21. start!
  22. Function Msg777
  23. Function Msg777
  24. Function Msg777
  25. Function Msg777
  26. Function Msg777
  27. Function Msg777
  28. Function Msg777
  29. Function Msg777
  30. Function Msg777
  31. Function Msg777

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/602446
推荐阅读
相关标签
  

闽ICP备14008679号