码迷,mamicode.com
首页 > 编程语言 > 详细

C++11多线程——<future>之std::promise学习

时间:2015-04-18 13:09:00      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:c++11   多线程   future   std   promise   

一  <future>头文件简介

1 Classes

std::future

std::future_error

std::packaged_task

std::promise

std::shared_future

2 Functions

std::async

std::future_category

二 std::promise类

1 std::promise class statement

Template <class T> promise;
Template <classR&> promise<R&> // specialization : T is a reference type(R&)
Template <> promise<void>;//specialization : T is void

2 introduce std::promise

Promise对象可保存T类型的值,该值可被future对象读取(可能在另一个线程中),这是promise提供的同步的一种手段。在构造promise时,promise对象可以与共享状态关联起来,这个共享状态可以存储一个T类型或者一个由std::exception派生出的类的值,并可以通过get_future来获取与promise对象关联的对象,调用该函数之后,两个对象共享相同的共享状态(shared state)

Promise对象是异步provider,它可以在某一时刻设置共享状态的值

Future对象可以返回共享状态的值,或者在必要的情况下阻塞调用者并等待共享状态标识变为ready,然后才能获取共享状态的值。

There is a simple example to explain above relations:

#include <iostream>//std::cout
#include <future>//std::promisestd::future
#include <thread>//std::thread
#include <functional>//std::ref
 
void printInt(std::future<int>&fut)
{
        int x = fut.get();
        std::cout << "value ="<< x << "\n";
}
 
int main(int argc, _TCHAR* argv[])
{
        std::promise<int> prom;
        std::future<int>fut =prom.get_future();//将prom与fut关联
        std::thread th(printInt,std::ref(fut));//新建线程,执行printInt函数
 
        prom.set_value(10);//设置共享状态的值
        th.join();
        return 0;
}

 

         3 std::promise constructor

Default(1)                  promise()
With allocator(2)           template<class Alloc>promise(allocator_arg_t,aa,const Alloc&alloc);
Copy[delete](3)             promise(constpromise&) = delete;
Move(4)                     promise(constpromise&&x)noexcept;

(1)  Default constructor

初始化一个空的共享状态

(2)  Constructor with allocator

与默认构造函数类似,但是使用自定义的分配器分配共享状态

(3)  Copy constructor [delete]

(4)    Move constructor

 There is aexample to explain the std::promise constructor:

//promise constructors
#include <iostream>       // std::cout
#include <functional>     // std::ref
#include <memory>         // std::allocator,std::allocator_arg
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
 
void print_int(std::future<int>& fut) {
        int x = fut.get();
        std::cout << "value: " << x << '\n';
}
 
int main()
{
        std::promise<int> foo;
        std::promise<int> bar = std::promise<int>(std::allocator_arg,std::allocator<int>());
 
        std::future<int> fut =bar.get_future();
 
        std::thread th(print_int,std::ref(fut));
 
        bar.set_value(20);
 
        th.join();
        return 0;
}


4 std::promise member functions

         4.1std::promise::get_future

改函数返回一个与promise共享状态相关联的future对象。返回的future对象可以访问由promise对象设置在共享状态的值或某异常对象。且只能从promise对象的共享状态获取一个future对象。调用该函数之后,promise对象通常会在某个时间点设置好(一个值或者一个异常对象),如果不设置值或异常,promise在析构时会自动的设置一个future_error异常来设置自身的准备状态。

         4.2 std::promise::set_value

Generictemplate            void set_value(constT& val)
                           void set_value(T&& val)
specializations            void promise<R&>::set_value(R&val)
                           void promise<void>::set_value(void)

设置共享状态的值,此后promise共享状态标识变为ready

         4.3std::promise::set_exception

为promise设置异常,此后promise的共享状态标识变为ready

                  

                   Example:

//promise::set_exception
#include <iostream>       // std::cin, std::cout,std::ios
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
#include <exception>      // std::exception, std::current_exception
 
void get_int(std::promise<int>& prom) {
        int x;
        std::cout << "Please, enteran integer value: ";
        std::cin.exceptions(std::ios::failbit);   // throw on failbit
        try {
                  std::cin >> x;                           // sets failbit ifinput is not int
                  prom.set_value(x);
        }
        catch (std::exception&) {
                  prom.set_exception(std::current_exception());
        }
}
 
void print_int(std::future<int>& fut) {
        try {
                  int x = fut.get();
                  std::cout << "value: " << x << '\n';
        }
        catch (std::exception& e) {
                  std::cout << "[exceptioncaught: "<< e.what() << "]\n";
        }
}
 
int main()
{
        std::promise<int> prom;
        std::future<int> fut =prom.get_future();
 
        std::thread th1(print_int,std::ref(fut));
        std::thread th2(get_int,std::ref(prom));
 
        th1.join();
        th2.join();
        return 0;
}


         4.4 std::promise::set_value_at_thread_exit

设置共享状态的值,但不是立刻设置,而是在线程退出时,promise自动设置共享状态的值。若某future对象与promise对象相关联,并且该future对象正在调用get,则调用get的线程会被阻塞,当线程退出时,调用future::get的线程自动解除阻塞,同时返回promise::set_value_at_thread_exit所设置的值

注意:该线程以设置promise的值,如果在线程结束之后有其他修改共享状态值得操作,会抛出future_error(promise_already_satisfied)异常

 

         4.5 std::promise::operator = (移动赋值)

//promise::operator=
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
 
std::promise<int> prom;
 
voidprint_global_promise() {
        std::future<int> fut =prom.get_future();
        int x = fut.get();
        std::cout << "value: " << x << '\n';
}
 
int main()
{
        std::threadth1(print_global_promise);
        prom.set_value(10);
        th1.join();
 
        prom = std::promise<int>();    // reset, by move-assigning a new promise
 
        std::threadth2(print_global_promise);
        prom.set_value(20);
        th2.join();
 
        return 0;
}


         4.6 std::promise::swap(non-member-overloads)

                   交换两个promise的共享状态

C++11多线程——<future>之std::promise学习

标签:c++11   多线程   future   std   promise   

原文地址:http://blog.csdn.net/u013507368/article/details/45112071

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!