Stdpackaged Task Class In C++ - C++ Programming Tutorial
C++ Course / Object-Oriented Programming / Stdpackaged Task Class In C++

Stdpackaged Task Class In C++

BLUF: Mastering Stdpackaged Task Class In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Stdpackaged Task Class In C++

C++ is renowned for its efficiency. Learn how Stdpackaged Task Class In C++ enables low-level control and high-performance computing in the tutorial below.

In this guide, we will explore the std::packaged_task class in C++ along with its syntax, arguments, methods, and a demonstration.

What is the std::packaged_task class in C++?

In C++, various callable entities like functions, lambda expressions, bind expressions, and any function object can be encapsulated and executed concurrently using the std::packagedtask class. Unlike some alternate methods of asynchronous execution such as std::async, a std::packagedtask doesn't commence execution automatically upon instantiation. Rather, it remains inactive until explicitly triggered.

Once a std::packaged_task is called, the associated function starts running, and any outcome or error from the operation is saved in a common state. In case of an issue during the process, it can be dealt with asynchronously by fetching the outcome through a std::future instance, which allows interaction with this shared state.

Syntax:

It has the following syntax:

Example

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

Parameters:

  • Template: Two template parameters and a template class are declared in this way.
  • R: R is a representation of the function's return type related to the packed task.
  • Args..: The sorts of arguments that the Function associated with the packed task accepts are represented by the parameter pack called Args. Args can represent zero or more template arguments because it is a variadic template parameter, as indicated by the ellipsis (...).
  • Packagedtask class: This is the actual class declaration. It indicates that a function type R(Args...), where Args... is the parameter pack that represents the kinds of arguments and R is the return type, and defines the packagedtask class template.
  • Return Value:

The output of std::packaged_task is an instance representing a job linked to a callable object with the signature R(Args...). This facilitates the asynchronous running of the task and fetching its outcome using a linked std::future.

Consider the following scenario:

Imagine a situation where a current function is tasked with fetching and delivering data from a Database (DB). Suppose this function needs to run in a distinct thread to avoid obstructing the primary execution thread.

In such scenarios, utilizing the std::packaged_task offers benefits. Wrapping the database retrieval function within a packaged task enables us to execute it concurrently on a separate thread, ensuring that the associated future object promptly manages the outcome and any possible errors.

Member Functions:

  • Operator=: This is the assignment operator(=) overloaded for std::packagedtask. It allows us to move one std::packagedtask object to another, transferring ownership of its state.
  • Swap: This member function swaps the contents of two std::packaged_task objects, which exchange their state. It can be useful for efficiently exchanging the state of two tasks.
  • Getfuture: This member function returns a std::future object associated with the promised result of the std::packagedtask. It allows us to asynchronously retrieve the result or handle exceptions.
  • Reset: This member function resets the std::packaged_task object. It clears any state associated with the task, which makes it ready for reuse.
  • Constructor: The constructor initializes a std::packaged_task object, which is usually takes a callable object as a parameter.
  • Destructor: The destructor deallocates resources associated with the std::packaged_task object when it goes out of scope.
  • Example:

Let's consider an illustration to demonstrate the std::packaged_task in C++.

Example

#include <iostream>
#include <future>
#include <thread>
#include <vector>
#include <numeric>
//Function to calculate the sum of elements in a vector
int SumVector(const std::vector<int>& vec) 
{
    return std::accumulate(vec.begin(), vec.end(), 0);
}
int main()
{
    // Creating a vector of integers.
    std::vector<int> nums = {18, 29, 32, 45, 60};
    // Creating a packaged_task to calculate the sum of the vector elements.
    std::packaged_task<int(const std::vector<int>&)> task(SumVector);
    // Get the associated future object.
    std::future<int> future = task.get_future();
    // Execute the task asynchronously.
    std::thread t(std::move(task), nums);
    t.join();
    // Get the result from the future.
    int result = future.get();
    // Displaying the result.
    std::cout << "The sum of the vector elements: " << result << std::endl;
    return 0;
}

Output:

Output

The sum of the vector elements: 184

Explanation:

  • This example demonstrates the use of std::packaged_task for asynchronous function execution. The SumVector function uses std::accumulate to determine the sum of the elements in a vector.
  • After creating and initializing a vector called nums, integers are used.
  • The SumVector method is used to create a std::packaged_task with the name task.
  • After that, the task produces the related std::future object future, which will store the result of the asynchronous computation.
  • Using std::move(task) function, the vector nums are passed in as a parameter, causing the task to be run asynchronously in a different thread, 't'.
  • Using t.join method, the main thread waits for the asynchronous task to be completed.
  • The get method is used to receive the result, which contains the sum of the vector elements from the future once the operation has been performed. The result is printed on the console.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience