当前位置:   article > 正文

关于std::async 的实验_std::async(std::launch::async,

std::async(std::launch::async,

std::async

std::async 会异步执行函数指针,lambda 表达式 以及 std::bind一类的结果 

类型主要有三个

std::launch::async
保证异步行为,即传递函数将在单独的线程中执行
·std::launch::deferred
当其他线程调用get()来访问共享状态时,将调用非异步行为
·std::launch::async | std::launch::deferred
 

看第一个例子:

  1. #include <unistd.h>
  2. #include <sys/syscall.h>
  3. #include <thread>
  4. #include <future>
  5. #include <string>
  6. #include <iostream>
  7. #include <chrono>
  8. std::string print1(std::string& str) {
  9. std::cout << syscall(SYS_gettid) << std::endl;
  10. std::cout << str << std::endl;
  11. str = "111";
  12. std::this_thread::sleep_for(std::chrono::seconds(5));
  13. return "ok";
  14. }
  15. //std::async
  16. int main()
  17. {
  18. std::cout << syscall(SYS_gettid) << std::endl;
  19. std::string str1 = "hello";
  20. auto future = std::async(std::launch::async, print1, std::ref(str1));
  21. std::cout << future.get() << std::endl;
  22. std::cout << str1 << std::endl;
  23. return 0;
  24. }

输出结果为

  1. root@e170efb889a0:/data/test/build# ./demo
  2. 2975
  3. 2976
  4. hello
  5. ok
  6. hahahah1
  7. root@e170efb889a0:/data/test/build# ./demo
  8. 3629
  9. 3630
  10. hello
  11. ok
  12. 111

我发现他是换了另一个线程去执行我当前的函数

再看第二个例子:

  1. #include <unistd.h>
  2. #include <sys/syscall.h>
  3. #include <thread>
  4. #include <future>
  5. #include <string>
  6. #include <iostream>
  7. #include <functional>
  8. #include <chrono>
  9. class A {
  10. public:
  11. std::string print(std::string& str) {
  12. std::cout << syscall(SYS_gettid) << std::endl;
  13. std::cout << str << std::endl;
  14. str = "111";
  15. std::this_thread::sleep_for(std::chrono::seconds(5));
  16. return "ok";
  17. }
  18. };
  19. // std::string print1(std::string& str) {
  20. // std::cout << syscall(SYS_gettid) << std::endl;
  21. // std::cout << str << std::endl;
  22. // str = "111";
  23. // std::this_thread::sleep_for(std::chrono::seconds(5));
  24. // return "ok";
  25. // }
  26. //std::async
  27. int main()
  28. {
  29. A* ptr = new A();
  30. std::cout << syscall(SYS_gettid) << std::endl;
  31. std::string str1 = "hello";
  32. auto future = std::async(std::launch::deferred, std::bind(&A::print, ptr, std::ref(str1)));
  33. std::cout << future.get() << std::endl;
  34. std::cout << str1 << std::endl;
  35. return 0;
  36. }

查看运行结果

  1. root@e170efb889a0:/data/test/build# ./demo 
  2. 4242
  3. 4242
  4. hello
  5. ok
  6. 111


我们发现是在同一个线程运行的,注意一个点std::ref

bind()是一个函数模板,它的原理是根据已有的模板,生成一个函数,但是由于bind()不知道生成的函数执行的时候,传递进来的参数是否还有效。所以它选择参数值传递而不是引用传递。如果想引用传递,std::ref和std::cref就派上用场了。

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

闽ICP备14008679号