赞
踩
std::async
std::async 会异步执行函数指针,lambda 表达式 以及 std::bind一类的结果
类型主要有三个
std::launch::async
保证异步行为,即传递函数将在单独的线程中执行
·std::launch::deferred
当其他线程调用get()来访问共享状态时,将调用非异步行为
·std::launch::async | std::launch::deferred
看第一个例子:
-
- #include <unistd.h>
- #include <sys/syscall.h>
- #include <thread>
- #include <future>
- #include <string>
- #include <iostream>
- #include <chrono>
-
- std::string print1(std::string& str) {
- std::cout << syscall(SYS_gettid) << std::endl;
- std::cout << str << std::endl;
-
- str = "111";
- std::this_thread::sleep_for(std::chrono::seconds(5));
- return "ok";
- }
-
- //std::async
- int main()
- {
- std::cout << syscall(SYS_gettid) << std::endl;
- std::string str1 = "hello";
- auto future = std::async(std::launch::async, print1, std::ref(str1));
- std::cout << future.get() << std::endl;
- std::cout << str1 << std::endl;
-
- return 0;
- }
输出结果为
- root@e170efb889a0:/data/test/build# ./demo
- 2975
- 2976
- hello
- ok
- hahahah1
- root@e170efb889a0:/data/test/build# ./demo
- 3629
- 3630
- hello
- ok
- 111
我发现他是换了另一个线程去执行我当前的函数
再看第二个例子:
-
- #include <unistd.h>
- #include <sys/syscall.h>
- #include <thread>
- #include <future>
- #include <string>
- #include <iostream>
- #include <functional>
- #include <chrono>
-
- class A {
- public:
- std::string print(std::string& str) {
- std::cout << syscall(SYS_gettid) << std::endl;
- std::cout << str << std::endl;
-
- str = "111";
- std::this_thread::sleep_for(std::chrono::seconds(5));
- return "ok";
- }
- };
-
- // std::string print1(std::string& str) {
- // std::cout << syscall(SYS_gettid) << std::endl;
- // std::cout << str << std::endl;
-
- // str = "111";
- // std::this_thread::sleep_for(std::chrono::seconds(5));
- // return "ok";
- // }
-
- //std::async
- int main()
- {
- A* ptr = new A();
- std::cout << syscall(SYS_gettid) << std::endl;
- std::string str1 = "hello";
- auto future = std::async(std::launch::deferred, std::bind(&A::print, ptr, std::ref(str1)));
- std::cout << future.get() << std::endl;
- std::cout << str1 << std::endl;
-
- return 0;
- }
查看运行结果
- root@e170efb889a0:/data/test/build# ./demo
- 4242
- 4242
- hello
- ok
- 111
我们发现是在同一个线程运行的,注意一个点std::ref
bind()是一个函数模板,它的原理是根据已有的模板,生成一个函数,但是由于bind()不知道生成的函数执行的时候,传递进来的参数是否还有效。所以它选择参数值传递而不是引用传递。如果想引用传递,std::ref和std::cref就派上用场了。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。