std::thread:
std::thread是一个 c++ 对象,其可以表示一个正在运行的线程。但是,当处于下面这些状态时, std::thread 对象与一个运行的线程没有任何关系:
- default construction 之后
- move from 之后(不能别copy)
- detach, or join 之后
注意:与一个 std::thread 对象关联的线程在该 std::thread对象构造好之后立即运行。
另外,std::thread 没有全部实现底层操作系统的thread相关接口。例如设置 CPU affinity 等。但是 std::thread::native_handle()
暴露了一个底层thread的句柄,通过该句柄可以直接操作该线程。
boost::future::then:
boost::future
has also support for .then
, which allows you to append a continuation to a future
, which will be exectuted after the successfull execution of the code inside the future.
std::future
不支持添加 continuation,没有 .then
的调用,不过也很方便使用。
see link:
http://www.tuicool.com/articles/6j2u2qa
http://blog.csdn.net/gw569453350game/article/details/50052909
如何编写异步执行的程序(main.cpp):
#include <iostream>
#include <string>
#include <future> // std::promise, std::future, std::async
using namespace std;
int main()
{
// 注意,如果不用一个变量f1保存返回的future,则默认构造的future会马上被销毁,销毁过程中会阻塞等待线程被执行完。
std::future<std::string> f1 = std::async(std::launch::async, [](){
return std::string("hello, world"); // 创建线程, 设定 promise, 返回一个 future。区别于 std::launch::deferred(不会创建新的线程去执行该lambda函数,其实最好是使用 deferred 策略,否则可能出现内存问题,see link: https://svn.boost.org/trac/boost/ticket/12220)
});
std::vector< std::future<std::string> > vf;
vf.push_back(std::move(f1)); // future不能够被复制,但是可以被move
cout<<vf[0].get()<<endl; // get 方法阻塞,直到执行完成并返回结果,output: hello, world
std::future<int> f2 = std::async(std::launch::async, [](){
cout<<8<<endl;
return 8;
});
f2.wait(); //wait 方法等待执行完成,不返回结果
std::future<int> future = std::async(std::launch::async, [](){
std::this_thread::sleep_for(std::chrono::seconds(3));
return 8;
});
std::cout << "waiting...\n";
std::future_status status;
do {
status = future.wait_for(std::chrono::seconds(1));
if (status == std::future_status::deferred) {
std::cout << "deferred\n";
} else if (status == std::future_status::timeout) {
std::cout << "timeout\n";
} else if (status == std::future_status::ready) {
std::cout << "ready!\n";
}
} while (status != std::future_status::ready);
std::cout << "result is " << future.get() << '\n';
}
编译&运行:
g++ main.cpp -std=c++11 -pthread
./a.out
Output:
hello, world
8
waiting...
timeout
timeout
ready!
result is 8
多线程编程的常见错误:
https://www.acodersjourney.com/top-20-cplusplus-multithreading-mistakes/