Namespaces
Variants

std:: promise

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
promise
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
헤더 파일에 정의됨 <future>
template < class R > class promise ;
(1) (C++11부터)
template < class R > class promise < R & > ;
(2) (C++11부터)
template <> class promise < void > ;
(3) (C++11부터)
1) 기본 템플릿.
2) 비-보이드 특수화, 스레드 간 객체 통신에 사용됩니다.
3) void 전문화, 상태 비저장 이벤트 통신에 사용됩니다.

클래스 템플릿 std::promise 는 나중에 std::promise 객체에 의해 생성된 std::future 객체를 통해 비동기적으로 획득되는 값이나 예외를 저장하는 기능을 제공합니다. std::promise 객체는 한 번만 사용하도록 의도되었습니다.

각 프라미스는 shared state 와 연결되어 있으며, 이는 일부 상태 정보와 아직 평가되지 않았거나, 값(void일 수 있음)으로 평가되었거나, 예외로 평가된 result 를 포함합니다. 프라미스는 shared state에 대해 세 가지 작업을 수행할 수 있습니다:

  • make ready : promise가 결과나 예외를 공유 상태에 저장합니다. 상태를 준비 완료로 표시하고 공유 상태와 연결된 future를 대기 중인 모든 스레드의 차단을 해제합니다.
  • release : promise가 공유 상태에 대한 참조를 포기합니다. 이것이 마지막 참조였다면 공유 상태는 파괴됩니다. 아직 준비되지 않은 std:: async 에 의해 생성된 공유 상태가 아닌 경우, 이 작업은 블록되지 않습니다.
  • abandon : promise가 std::future_error 타입의 예외를 오류 코드 std::future_errc::broken_promise 와 함께 저장하고, 공유 상태를 ready 로 만든 후 releases 합니다.

프라미스(promise)는 프라미스-퓨처(promise-future) 통신 채널의 "푸시(push)" 단입니다: 공유 상태에 값을 저장하는 연산은 동기화됩니다(synchronizes-with) ( std::memory_order 에 정의된 대로) 공유 상태를 대기하는 모든 함수(예: std::future::get )의 성공적인 반환과. 그렇지 않으면 동일한 공유 상태에 대한 동시 접근은 충돌할 수 있습니다: 예를 들어 std::shared_future::get 의 다중 호출자는 모두 읽기 전용이거나 외부 동기화를 제공해야 합니다.

목차

멤버 함수

promise 객체를 생성합니다
(public member function)
promise 객체를 소멸합니다
(public member function)
공유 상태를 할당합니다
(public member function)
두 promise 객체를 교환합니다
(public member function)
결과 얻기
약속된 결과와 연관된 future 를 반환합니다
(public member function)
결과 설정
결과를 특정 값으로 설정합니다
(public member function)
결과를 특정 값으로 설정하며 스레드 종료 시에만 알림을 전달합니다
(public member function)
결과를 예외를 나타내도록 설정합니다
(public member function)
결과를 예외를 나타내도록 설정하며 스레드 종료 시에만 알림을 전달합니다
(public member function)

비멤버 함수

std::swap 알고리즘을 특수화함
(함수 템플릿)

헬퍼 클래스

std::uses_allocator 타입 특성의 특수화
(클래스 템플릿 특수화)

예제

이 예제는 promise<int> 가 스레드 간 신호로 어떻게 사용될 수 있는지 보여줍니다.

#include <chrono>
#include <future>
#include <iostream>
#include <numeric>
#include <thread>
#include <vector>
void accumulate(std::vector<int>::iterator first,
                std::vector<int>::iterator last,
                std::promise<int> accumulate_promise)
{
    int sum = std::accumulate(first, last, 0);
    accumulate_promise.set_value(sum); // Notify future
}
void do_work(std::promise<void> barrier)
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    barrier.set_value();
}
int main()
{
    // Demonstrate using promise<int> to transmit a result between threads.
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6};
    std::promise<int> accumulate_promise;
    std::future<int> accumulate_future = accumulate_promise.get_future();
    std::thread work_thread(accumulate, numbers.begin(), numbers.end(),
                            std::move(accumulate_promise));
    // future::get() will wait until the future has a valid result and retrieves it.
    // Calling wait() before get() is not needed
    // accumulate_future.wait(); // wait for result
    std::cout << "result=" << accumulate_future.get() << '\n';
    work_thread.join(); // wait for thread completion
    // Demonstrate using promise<void> to signal state between threads.
    std::promise<void> barrier;
    std::future<void> barrier_future = barrier.get_future();
    std::thread new_work_thread(do_work, std::move(barrier));
    barrier_future.wait();
    new_work_thread.join();
}

출력:

result=21