A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://timsong-cpp.github.io/cppwp/n4659/futures below:

33 Thread support library [thread]

33 Thread support library [thread] 33.6 Futures [futures] 33.6.1 Overview [futures.overview]

[futures] describes components that a C++ program can use to retrieve in one thread the result (value or exception) from a function that has run in the same thread or another thread. [Note: These components are not restricted to multi-threaded programs but can be useful in single-threaded programs as well. end note]

33.6.2 Header <future> synopsis [future.syn]
namespace std {
  enum class future_errc {
    broken_promise = implementation-defined,
    future_already_retrieved = implementation-defined,
    promise_already_satisfied = implementation-defined,
    no_state = implementation-defined
  };

  enum class launch : unspecified {
    async = unspecified,
    deferred = unspecified,
    implementation-defined
  };

  enum class future_status {
    ready,
    timeout,
    deferred
  };

  template <> struct is_error_code_enum<future_errc> : public true_type { };
  error_code make_error_code(future_errc e) noexcept;
  error_condition make_error_condition(future_errc e) noexcept;

  const error_category& future_category() noexcept;

  class future_error;

  template <class R> class promise;
  template <class R> class promise<R&>;
  template <> class promise<void>;

  template <class R>
    void swap(promise<R>& x, promise<R>& y) noexcept;

  template <class R, class Alloc>
    struct uses_allocator<promise<R>, Alloc>;

  template <class R> class future;
  template <class R> class future<R&>;
  template <> class future<void>;

  template <class R> class shared_future;
  template <class R> class shared_future<R&>;
  template <> class shared_future<void>;

  template <class> class packaged_task;     template <class R, class... ArgTypes>
    class packaged_task<R(ArgTypes...)>;

  template <class R, class... ArgTypes>
    void swap(packaged_task<R(ArgTypes...)>&, packaged_task<R(ArgTypes...)>&) noexcept;

  template <class R, class Alloc>
    struct uses_allocator<packaged_task<R>, Alloc>;

  template <class F, class... Args>
    future<invoke_result_t<decay_t<F>, decay_t<Args>...>>
    async(F&& f, Args&&... args);
  template <class F, class... Args>
    future<invoke_result_t<decay_t<F>, decay_t<Args>...>>
    async(launch policy, F&& f, Args&&... args);
}

The enum type launch is a bitmask type with elements launch​::​async and launch​::​deferred. [Note: Implementations can provide bitmasks to specify restrictions on task interaction by functions launched by async() applicable to a corresponding subset of available launch policies. Implementations can extend the behavior of the first overload of async() by adding their extensions to the launch policy under the “as if” rule. end note]

The enum values of future_­errc are distinct and not zero.

33.6.3 Error handling [futures.errors]

const error_category& future_category() noexcept;

Returns:  A reference to an object of a type derived from class error_­category.

The object's default_­error_­condition and equivalent virtual functions shall behave as specified for the class error_­category. The object's name virtual function shall return a pointer to the string "future".

error_code make_error_code(future_errc e) noexcept;

Returns: error_­code(static_­cast<int>(e), future_­category()).

error_condition make_error_condition(future_errc e) noexcept;

Returns: error_­condition(static_­cast<int>(e), future_­category()).

33.6.4 Class future_­error [futures.future_error]
namespace std {
  class future_error : public logic_error {
  public:
    explicit future_error(future_errc e);

    const error_code& code() const noexcept;
    const char*       what() const noexcept;
  private:
    error_code ec_;    };
}

explicit future_error(future_errc e);

Effects: Constructs an object of class future_­error and initializes ec_­ with make_­error_­code(e).

const error_code& code() const noexcept;

const char* what() const noexcept;

Returns: An ntbs incorporating code().message().

33.6.5 Shared state [futures.state]

Many of the classes introduced in this subclause use some state to communicate results. This consists of some state information and some (possibly not yet evaluated) result, which can be a (possibly void) value or an exception. [Note: Futures, promises, and tasks defined in this clause reference such shared state. end note]

[Note: The result can be any kind of object including a function to compute that result, as used by async when policy is launch​::​deferred. end note]

An asynchronous provider is an object that provides a result to a shared state. The result of a shared state is set by respective functions on the asynchronous provider. [Note: Such as promises or tasks. end note] The means of setting the result of a shared state is specified in the description of those classes and functions that create such a state object.

When an asynchronous return object or an asynchronous provider is said to release its shared state, it means:

When an asynchronous provider is said to make its shared state ready, it means:

When an asynchronous provider is said to abandon its shared state, it means:

A shared state is ready only if it holds a value or an exception ready for retrieval. Waiting for a shared state to become ready may invoke code to compute the result on the waiting thread if so specified in the description of the class or function that creates the state object.

Calls to functions that successfully set the stored result of a shared state synchronize with calls to functions successfully detecting the ready state resulting from that setting. The storage of the result (whether normal or exceptional) into the shared state synchronizes with the successful return from a call to a waiting function on the shared state.

Some functions (e.g., promise​::​set_­value_­at_­thread_­exit) delay making the shared state ready until the calling thread exits. The destruction of each of that thread's objects with thread storage duration is sequenced before making that shared state ready.

Access to the result of the same shared state may conflict. [Note: This explicitly specifies that the result of the shared state is visible in the objects that reference this state in the sense of data race avoidance. For example, concurrent accesses through references returned by shared_­future​::​get() ([futures.shared_future]) must either use read-only operations or provide additional synchronization. end note]

33.6.6 Class template promise [futures.promise]
namespace std {
  template <class R>
  class promise {
  public:
    promise();
    template <class Allocator>
      promise(allocator_arg_t, const Allocator& a);
    promise(promise&& rhs) noexcept;
    promise(const promise& rhs) = delete;
    ~promise();

        promise& operator=(promise&& rhs) noexcept;
    promise& operator=(const promise& rhs) = delete;
    void swap(promise& other) noexcept;

        future<R> get_future();

        void set_value(see below);
    void set_exception(exception_ptr p);

        void set_value_at_thread_exit(see below);
    void set_exception_at_thread_exit(exception_ptr p);
  };
  template <class R>
    void swap(promise<R>& x, promise<R>& y) noexcept;
  template <class R, class Alloc>
    struct uses_allocator<promise<R>, Alloc>;
}

The implementation shall provide the template promise and two specializations, promise<R&> and promise<​void>. These differ only in the argument type of the member functions set_­value and set_­value_­at_­thread_­exit, as set out in their descriptions, below.

The set_­value, set_­exception, set_­value_­at_­thread_­exit, and set_­exception_­at_­thread_­exit member functions behave as though they acquire a single mutex associated with the promise object while updating the promise object.

template <class R, class Alloc> struct uses_allocator<promise<R>, Alloc> : true_type { };

promise(); template <class Allocator> promise(allocator_arg_t, const Allocator& a);

Effects: constructs a promise object and a shared state. The second constructor uses the allocator a to allocate memory for the shared state.

promise(promise&& rhs) noexcept;

Effects: constructs a new promise object and transfers ownership of the shared state of rhs (if any) to the newly-constructed object.

Postconditions: rhs has no shared state.

~promise();

promise& operator=(promise&& rhs) noexcept;

Effects: Abandons any shared state ([futures.state]) and then as if promise(std​::​move(rhs)).swap(*this).

void swap(promise& other) noexcept;

Effects: Exchanges the shared state of *this and other.

Postconditions: *this has the shared state (if any) that other had prior to the call to swap. other has the shared state (if any) that *this had prior to the call to swap.

future<R> get_future();

Returns: A future<R> object with the same shared state as *this.

Throws: future_­error if *this has no shared state or if get_­future has already been called on a promise with the same shared state as *this.

Error conditions:

void promise::set_value(const R& r); void promise::set_value(R&& r); void promise<R&>::set_value(R& r); void promise<void>::set_value();

Effects: Atomically stores the value r in the shared state and makes that state ready ([futures.state]).

Throws:

Error conditions:

void set_exception(exception_ptr p);

Effects: Atomically stores the exception pointer p in the shared state and makes that state ready ([futures.state]).

Throws: future_­error if its shared state already has a stored value or exception.

Error conditions:

void promise::set_value_at_thread_exit(const R& r); void promise::set_value_at_thread_exit(R&& r); void promise<R&>::set_value_at_thread_exit(R& r); void promise<void>::set_value_at_thread_exit();

Effects: Stores the value r in the shared state without making that state ready immediately. Schedules that state to be made ready when the current thread exits, after all objects of thread storage duration associated with the current thread have been destroyed.

Throws:

Error conditions:

void set_exception_at_thread_exit(exception_ptr p);

Effects: Stores the exception pointer p in the shared state without making that state ready immediately. Schedules that state to be made ready when the current thread exits, after all objects of thread storage duration associated with the current thread have been destroyed.

Throws: future_­error if an error condition occurs.

Error conditions:

template <class R> void swap(promise<R>& x, promise<R>& y) noexcept;

Effects: As if by x.swap(y).

33.6.7 Class template future [futures.unique_future]

The class template future defines a type for asynchronous return objects which do not share their shared state with other asynchronous return objects. A default-constructed future object has no shared state. A future object with shared state can be created by functions on asynchronous providers or by the move constructor and shares its shared state with the original asynchronous provider. The result (value or exception) of a future object can be set by calling a respective function on an object that shares the same shared state.

[Note: Member functions of future do not synchronize with themselves or with member functions of shared_­future. end note]

The effect of calling any member function other than the destructor, the move-assignment operator, share, or valid on a future object for which valid() == false is undefined. [Note: It is valid to move from a future object for which valid() == false. end note] [Note: Implementations are encouraged to detect this case and throw an object of type future_­error with an error condition of future_­errc​::​no_­state. end note]

namespace std {
  template <class R>
  class future {
  public:
    future() noexcept;
    future(future&&) noexcept;
    future(const future& rhs) = delete;
    ~future();
    future& operator=(const future& rhs) = delete;
    future& operator=(future&&) noexcept;
    shared_future<R> share() noexcept;

        see below get();

        bool valid() const noexcept;

    void wait() const;
    template <class Rep, class Period>
      future_status wait_for(const chrono::duration<Rep, Period>& rel_time) const;
    template <class Clock, class Duration>
      future_status wait_until(const chrono::time_point<Clock, Duration>& abs_time) const;
  };
}

The implementation shall provide the template future and two specializations, future<R&> and future<​void>. These differ only in the return type and return value of the member function get, as set out in its description, below.

future() noexcept;

Effects: Constructs an empty future object that does not refer to a shared state.

Postconditions: valid() == false.

future(future&& rhs) noexcept;

Effects: Move constructs a future object that refers to the shared state that was originally referred to by rhs (if any).

Postconditions:

~future();

future& operator=(future&& rhs) noexcept;

Effects:

Postconditions:

shared_future<R> share() noexcept;

Returns: shared_­future<R>(std​::​move(*this)).

Postconditions: valid() == false.

R future::get(); R& future<R&>::get(); void future<void>::get();

[Note: As described above, the template and its two required specializations differ only in the return type and return value of the member function get. end note]

Effects:

Returns:

Throws: the stored exception, if an exception was stored in the shared state.

Postconditions: valid() == false.

bool valid() const noexcept;

Returns: true only if *this refers to a shared state.

void wait() const;

Effects: Blocks until the shared state is ready.

template <class Rep, class Period> future_status wait_for(const chrono::duration<Rep, Period>& rel_time) const;

Effects: None if the shared state contains a deferred function ([futures.async]), otherwise blocks until the shared state is ready or until the relative timeout ([thread.req.timing]) specified by rel_­time has expired.

Returns:

template <class Clock, class Duration> future_status wait_until(const chrono::time_point<Clock, Duration>& abs_time) const;

Effects: None if the shared state contains a deferred function ([futures.async]), otherwise blocks until the shared state is ready or until the absolute timeout ([thread.req.timing]) specified by abs_­time has expired.

Returns:

33.6.9 Function template async [futures.async]

The function template async provides a mechanism to launch a function potentially in a new thread and provides the result of the function in a future object with which it shares a shared state.

template <class F, class... Args> future<invoke_result_t<decay_t<F>, decay_t<Args>...>> async(F&& f, Args&&... args); template <class F, class... Args> future<invoke_result_t<decay_t<F>, decay_t<Args>...>> async(launch policy, F&& f, Args&&... args);

Requires: F and each Ti in Args shall satisfy the MoveConstructible requirements, and

INVOKE(DECAY_COPY(std::forward<F>(f)),
       DECAY_COPY(std::forward<Args>(args))...)     

shall be a valid expression.

Effects: The first function behaves the same as a call to the second function with a policy argument of launch​::​async | launch​::​deferred and the same arguments for F and Args. The second function creates a shared state that is associated with the returned future object. The further behavior of the second function depends on the policy argument as follows (if more than one of these conditions applies, the implementation may choose any of the corresponding policies):

Returns: An object of type future<invoke_­result_­t<decay_­t<F>, decay_­t<Args>...>> that refers to the shared state created by this call to async. [Note: If a future obtained from async is moved outside the local scope, other code that uses the future must be aware that the future's destructor may block for the shared state to become ready. end note]

Synchronization: Regardless of the provided policy argument,

If the implementation chooses the launch​::​async policy,

Throws: system_­error if policy == launch​::​async and the implementation is unable to start a new thread, or std​::​bad_­alloc if memory for the internal data structures could not be allocated.

Error conditions:

[Example:

int work1(int value);
int work2(int value);
int work(int value) {
  auto handle = std::async([=]{ return work2(value); });
  int tmp = work1(value);
  return tmp + handle.get();    }

[Note: Line #1 might not result in concurrency because the async call uses the default policy, which may use launch​::​deferred, in which case the lambda might not be invoked until the get() call; in that case, work1 and work2 are called on the same thread and there is no concurrency. end note] end example]

33.6.10 Class template packaged_­task [futures.task]

The class template packaged_­task defines a type for wrapping a function or callable object so that the return value of the function or callable object is stored in a future when it is invoked.

When the packaged_­task object is invoked, its stored task is invoked and the result (whether normal or exceptional) stored in the shared state. Any futures that share the shared state will then be able to access the stored result.

namespace std {
  template<class> class packaged_task; 
  template<class R, class... ArgTypes>
  class packaged_task<R(ArgTypes...)> {
  public:
        packaged_task() noexcept;
    template <class F>
      explicit packaged_task(F&& f);
    ~packaged_task();

        packaged_task(const packaged_task&) = delete;
    packaged_task& operator=(const packaged_task&) = delete;

        packaged_task(packaged_task&& rhs) noexcept;
    packaged_task& operator=(packaged_task&& rhs) noexcept;
    void swap(packaged_task& other) noexcept;

    bool valid() const noexcept;

        future<R> get_future();

        void operator()(ArgTypes... );
    void make_ready_at_thread_exit(ArgTypes...);

    void reset();
  };
  template <class R, class... ArgTypes>
    void swap(packaged_task<R(ArgTypes...)>& x, packaged_task<R(ArgTypes...)>& y) noexcept;
  template <class R, class Alloc>
    struct uses_allocator<packaged_task<R>, Alloc>;
}
33.6.10.1 packaged_­task member functions [futures.task.members]

packaged_task() noexcept;

Effects: Constructs a packaged_­task object with no shared state and no stored task.

template <class F> packaged_task(F&& f);

Requires: INVOKE<R>(f, t1, t2, ..., tN), where t1, t2, ..., tN are values of the corresponding types in ArgTypes..., shall be a valid expression. Invoking a copy of f shall behave the same as invoking f.

Remarks: This constructor shall not participate in overload resolution if decay_­t<F> is the same type as packaged_­task<R(ArgTypes...)>.

Effects: Constructs a new packaged_­task object with a shared state and initializes the object's stored task with std​::​forward<F>(f).

Throws:

packaged_task(packaged_task&& rhs) noexcept;

Effects: Constructs a new packaged_­task object and transfers ownership of rhs's shared state to *this, leaving rhs with no shared state. Moves the stored task from rhs to *this.

Postconditions: rhs has no shared state.

packaged_task& operator=(packaged_task&& rhs) noexcept;

Effects:

~packaged_task();

void swap(packaged_task& other) noexcept;

Effects: Exchanges the shared states and stored tasks of *this and other.

Postconditions: *this has the same shared state and stored task (if any) as other prior to the call to swap. other has the same shared state and stored task (if any) as *this prior to the call to swap.

bool valid() const noexcept;

Returns: true only if *this has a shared state.

future<R> get_future();

Returns: A future object that shares the same shared state as *this.

Throws: a future_­error object if an error occurs.

Error conditions:

void operator()(ArgTypes... args);

Effects: As if by INVOKE<R>(f, t1, t2, ..., tN), where f is the stored task of *this and t1, t2, ..., tN are the values in args.... If the task returns normally, the return value is stored as the asynchronous result in the shared state of *this, otherwise the exception thrown by the task is stored. The shared state of *this is made ready, and any threads blocked in a function waiting for the shared state of *this to become ready are unblocked.

Throws: a future_­error exception object if there is no shared state or the stored task has already been invoked.

Error conditions:

void make_ready_at_thread_exit(ArgTypes... args);

Effects: As if by INVOKE<R>(f, t1, t2, ..., tN), where f is the stored task and t1, t2, ..., tN are the values in args.... If the task returns normally, the return value is stored as the asynchronous result in the shared state of *this, otherwise the exception thrown by the task is stored. In either case, this shall be done without making that state ready ([futures.state]) immediately. Schedules the shared state to be made ready when the current thread exits, after all objects of thread storage duration associated with the current thread have been destroyed.

Throws: future_­error if an error condition occurs.

Error conditions:

void reset();

Effects: As if *this = packaged_­task(std​::​move(f)), where f is the task stored in *this. [Note: This constructs a new shared state for *this. The old state is abandoned ([futures.state]). end note]

Throws:

33.6.10.2 packaged_­task globals [futures.task.nonmembers]

template <class R, class... ArgTypes> void swap(packaged_task<R(ArgTypes...)>& x, packaged_task<R(ArgTypes...)>& y) noexcept;

Effects: As if by x.swap(y).

template <class R, class Alloc> struct uses_allocator<packaged_task<R>, Alloc> : true_type { };


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4