資源簡(jiǎn)介
c++11多線程編程庫(kù)中的future庫(kù)的使用實(shí)例,供多線程編程參考學(xué)習(xí)
代碼片段和文件信息
#include????????//?std::cout
#include??????//?std::ref
#include??????????//?std::thread
#include??????????//?std::promise?std::future
void?print_int(std::future&?fut)?{
int?x?=?fut.get();?//?獲取共享狀態(tài)的值.
std::cout?<“value:?“?<}
int?test_future_1()
{
std::promise?prom;?//?生成一個(gè)?std::promise?對(duì)象.
std::future?fut?=?prom.get_future();?//?和?future?關(guān)聯(lián).
std::thread?t(print_int?std::ref(fut));?//?將?future?交給另外一個(gè)線程t.
prom.set_value(10);?//?設(shè)置共享狀態(tài)的值?此處和線程t保持同步.設(shè)置在join之前
t.join();
return?0;
}
std::promise?prom2;
void?print_global_promise()?{
std::future?fut?=?prom2.get_future();
int?x?=?fut.get();
std::cout?<“value:?“?<}
int?test_future_2()
{
std::thread?th1(print_global_promise);
prom2.set_value(10);
th1.join();
prom2?=?std::promise();????//?prom?被move賦值為一個(gè)新的?promise?對(duì)象.
std::thread?th2(print_global_promise);
prom2.set_value(20);
th2.join();
return?0;
}
int?countdown(int?from?int?to)?{
for?(int?i?=?from;?i?!=?to;?--i)?{
std::cout?< std::this_thread::sleep_for(std::chrono::seconds(1
- 上一篇:c++11原子庫(kù)
- 下一篇:c++11互斥庫(kù)mutex的使用
評(píng)論
共有 條評(píng)論