The C++ standard library
C++11 introduced the header, which provides a mechanism for asynchronous programming, allowing a program to continue executing other tasks while waiting for an operation to complete. library is part of concurrent programming in the C++ standard library; it allows programmers to handle asynchronous operations in a cleaner and safer way.
The library defines several key types:
std::future: Represents the result of an asynchronous operation; can query the operation's status, get the result, or wait for completion.std::promise: Used withstd::futureto set the result of an asynchronous operation.std::packaged_task: Wraps a function or callable object so it can execute as an asynchronous task.
std::promise
std::promise is used to set the result of an asynchronous operation. It is paired with std::future .
Example
#include
#include
int
main
(
)
{
std
::
promise
<
int
prom;
std
::
future
<
int
fut
=prom.
get_future
(
)
;
// Set the result in another thread
std
::
thread
t
(
[
prom
]
(
)
{
prom.
set_value
(
10
)
;
}
)
;
// Wait for the result
std
::
cout
<<
"Future value: "
<<
fut.
get
(
)
<<
std
::
endl
;
t.
join
(
)
;
return
0
;
}
Output result:
Future value: 10
std::packaged_task
std::packaged_task wraps a function or callable object so it can execute as an asynchronous task.
Example
#include
#include
#include
int
compute_square_root
(
double
x
)
{
return
std
::
sqrt
(
x
)
;
}
int
main
(
)
{
std
::
packaged_task
<
double
(
double
)
task
(
compute_square_root
);
std
::
future
<
double
result
=task.
get_future
(
)
;
std
::
thread
th
(
std
::
move
(
task
)
,
9.0
)
;
std
::
cout
<<
"Result: "
<<
result.
get
(
)
<<
std
::
endl
;
th.
join
(
)
;
return
0
;
}
Output result:
Result: 3
std::async
std::async is a convenient function for launching asynchronous tasks. It can immediately return a std::future object.
Example
#include
#include
int
main
(
)
{
std
::
future
<
int
fut
=
std::
async
(
std
::
launch
::
async
,
[
]
(
int
x
)
{
return
x
x
;
}
,
5
)
;
std
::
cout
<<
"Result: "
<<
fut.
get
(
)
<<
std
::
endl
;
return
0
;
}
Output result:
Result: 25
Exception handling
When an asynchronous operation throws an exception,std::future captures this exception, and it can be re-thrown by calling .get() method.
Example
#include
#include
void
throw_exception
(
)
{
throw
std
::
runtime_error
(
"Exception thrown"
)
;
}
int
main
(
)
{
std
::
future
<
void
fut
=
std::
async
(
throw_exception
)
;
try
{
fut.
get
(
)
;
}
catch
(
const
std
::
exception
&
e
)
{
std
::
cout
<<
"Caught exception: "
<<
e.
what
(
)
<<
std
::
endl
;
}
return
0
;
}
Output result:
Caught exception: Exception thrown
library provides C++ programmers with a simple yet powerful way to do asynchronous programming. By using std::promise, std::packaged_task and std::async, we can easily implement concurrency and asynchronous operations in C++ programs. Meanwhile, the exception-handling mechanism also ensures program robustness.