Namespaces
Variants

std:: packaged_task

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
(C++11)
(C++11)
packaged_task
(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 >
class packaged_task ;
(1) (C++11부터)
(정의되지 않음)
template < class R, class ... ArgTypes >
class packaged_task < R ( ArgTypes... ) > ;
(2) (C++11부터)

클래스 템플릿 std::packaged_task 는 모든 Callable 대상(함수, 람다 표현식, 바인드 표현식, 또는 다른 함수 객체)을 비동기적으로 호출할 수 있도록 래핑합니다. 그 반환값이나 발생한 예외는 공유 상태에 저장되며, 이는 std::future 객체를 통해 접근할 수 있습니다.

std::function 과 마찬가지로, std::packaged_task 는 다형적이며 할당자 인식 컨테이너입니다: 저장된 호출 가능 대상은 힙에 할당되거나 제공된 할당자를 사용하여 할당될 수 있습니다.

(until C++17)

목차

멤버 함수

태스크 객체를 생성합니다
(public member function)
태스크 객체를 소멸합니다
(public member function)
태스크 객체를 이동합니다
(public member function)
태스크 객체가 유효한 함수를 가지고 있는지 확인합니다
(public member function)
두 태스크 객체를 교환합니다
(public member function)
결과 얻기
약속된 결과와 연관된 std::future 를 반환합니다
(public member function)
실행
함수를 실행합니다
(public member function)
현재 스레드가 종료될 때만 결과가 준비되도록 함수를 실행합니다
(public member function)
이전 실행의 저장된 결과를 버리고 상태를 재설정합니다
(public member function)

비멤버 함수

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

헬퍼 클래스

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

추론 가이드 (C++17부터)

예제

#include <cmath>
#include <functional>
#include <future>
#include <iostream>
#include <thread>
// std::pow 오버로드 집합의 모호함을 피하기 위한 고유 함수
int f(int x, int y) { return std::pow(x, y); }
void task_lambda()
{
    std::packaged_task<int(int, int)> task([](int a, int b)
    {
        return std::pow(a, b); 
    });
    std::future<int> result = task.get_future();
    task(2, 9);
    std::cout << "task_lambda:\t" << result.get() << '\n';
}
void task_bind()
{
    std::packaged_task<int()> task(std::bind(f, 2, 11));
    std::future<int> result = task.get_future();
    task();
    std::cout << "task_bind:\t" << result.get() << '\n';
}
void task_thread()
{
    std::packaged_task<int(int, int)> task(f);
    std::future<int> result = task.get_future();
    std::thread task_td(std::move(task), 2, 10);
    task_td.join();
    std::cout << "task_thread:\t" << result.get() << '\n';
}
int main()
{
    task_lambda();
    task_bind();
    task_thread();
}

출력:

task_lambda: 512
task_bind:   2048
task_thread: 1024

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 3117 C++17 packaged_task 에 대한 deduction guides가 누락됨 추가됨

참고 항목

(C++11)
비동기적으로 설정되는 값을 기다림
(클래스 템플릿)