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的共享状态

时间: 2024-08-25 16:14:37

C++11多线程——<future>之std::promise学习的相关文章

C++11 多线程 future/promise简介

1. < future >头文件简介 Classes std::future std::future_error std::packaged_task std::promise std::shared_future Functions std::async std::future_category 2. std::future 简单来说,std::future提供了一种访问异步操作结果的机制. 从字面意思看,它表示未来.通常一个异步操作我们是不能马上就获取操作结果的,只能在未来某个时候获取.我

c++11多线程记录1 -- std::thread

启动一个线程 话不多说,直接上代码 void func(); int main() { std::thread t(func); //这里就开始启动线程了 return 0; } void func() { std::cout << "Hello, " << std::this_thread::get_id() << std::endl; } 等待子线程结束 有时候开启一个子线程之后,父线程很快运行结束: 如果想要父线程做完自己的工作之后等待子线程运

c++11 使用异步编程std::async和std::future

先说明一点:std::asyanc是std::future的高级封装, 一般我们不会直接使用std::futrue,而是使用对std::future的高级封装std::async. 下面分别说一下. 一.std::async基本用法 std::future可以从异步任务中获取结果,一般与std::async配合使用,std::async用于创建异步任务,实际上就是创建一个线程执行相应任务. std::async就是异步编程的高级封装,封装了std::future的操作,基本上可以代替std::t

c/c++ 多线程 等待一次性事件 std::promise用法

多线程 等待一次性事件 std::promise用法 背景:不是很明白,不知道为了解决什么业务场景,感觉std::async可以优雅的搞定一切的一次等待性事件,为什么还有个std::promise. 用法:和std::async一样,也能够返回std::future,通过调用get_future方法.也可以通过future得到线程的返回值. 特点: 1,是个模板类,模板类型是个方法类型,比如double(int),有一个参数,类型是int,返回值类型是double. std::promise<i

C++11 并发指南一(C++11 多线程初探)(转)

引言 C++11 自2011年发布以来已经快两年了,之前一直没怎么关注,直到最近几个月才看了一些 C++11 的新特性,今后几篇博客我都会写一些关于 C++11 的特性,算是记录一下自己学到的东西吧,和大家共勉. 相信 Linux 程序员都用过 Pthread, 但有了 C++11 的 std::thread 以后,你可以在语言层面编写多线程程序了,直接的好处就是多线程程序的可移植性得到了很大的提高,所以作为一名 C++ 程序员,熟悉 C++11 的多线程编程方式还是很有益处的. 如果你对 C+

c++ 11 中future的一些理解

c++ 11 中 异步编程提供了很多新接口,大大简化了学习和使用成本,但是对应的,也引入了更多的基础概念.仔细理解这些概念,以及他们使用的场景,api中各个参数的含义,对于正确使用接口至关重要. 1. std::future 1.1 wait 1.2 wait_for 1.3 get 2. std::promise 3. std::packaged_task 4. std::async 5. 他们之间的关系可以用几句话简单的描述为: 5.0 官方的描述中,std::future std::pro

C++11多线程教学(二)

转载自:http://www.cnblogs.com/lidabo/p/3908713.html C++11多线程教学II 从我最近 发布的C++11线程教学文章里,我们已经知道C++11线程写法与POSIX的pthreads写法相比,更为简洁.只需很少几个简单概念,我们就能搭 建相当复杂的处理图片程序,但是我们回避了线程同步的议题.在接下来的部分,我们将进入C++11多线程编程的同步领域,看看如何来同步一组并行的线程. 我们快速回顾一下如何利用c++11创建线程组.上次教学当中,我们用传统c数

C++11多线程教学(一)

转载自:http://www.cnblogs.com/lidabo/p/3908705.html 本篇教学代码可在GitHub获得:https://github.com/sol-prog/threads. 在之前的教学中,我展示了一些最新进的C++11语言内容: 1. 正则表达式(http://solarianprogrammer.com/2011/10/12/cpp-11-regex-tutorial/) 2. raw string(http://solarianprogrammer.com/

C++11 多线程

C++11开始支持多线程编程,之前多线程编程都需要系统的支持,在不同的系统下创建线程需要不同的API如pthread_create(),Createthread(),beginthread()等,使用起来都比较复杂,C++11提供了新头文件<thread>.<mutex>.<atomic>.<future>等用于支持多线程. 使用C++11开启一个线程是比较简单的,下面来看一个简单的例子: #include <thread> #include &