Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Asynchrony and concurrency

Asynchrony separates submitting work from obtaining its result. Concurrency lets tasks make progress over overlapping periods, but does not guarantee parallel execution. In C++, std::async and std::future support this separation with an explicit waiting point.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

auto result = std::async(std::launch::async, callable);
auto value = result.get();

Asynchrony describes separating submission of an operation from retrieval of its result. Concurrency means multiple tasks make progress over overlapping periods; parallelism means they actually execute simultaneously. Concurrent threads need not execute in parallel, and an asynchronous interface does not guarantee a separate thread.

std::async(std::launch::async, callable) runs the function in a new thread and returns a std::future. Without an explicit policy, the implementation may choose std::launch::deferred: the first non-timed wait then runs the function in the waiting thread. Calling std::async alone therefore does not guarantee concurrent execution.

get() waits for readiness, returns the value or rethrows the stored exception, and invalidates that std::future; do not call it again without assigning a new state. Destroying the last object referring to an unready state created by std::async can block. Do not discard the temporary result if you want to preserve the opportunity for overlapping work.

Shared memory still needs synchronization: conflicting operations in different threads, at least one non-atomic, without a happens-before relationship constitute a data race and cause undefined behavior. The example avoids shared mutation: the task returns a value, and only the main thread prints after get().

This entry targets C++23; the supplied source is an evolving working draft, not a frozen C++23 publication. A repository compiler flag does not attest to production runtime behavior.

Examples

#include <future>
#include <iostream>

int main() {
    auto result = std::async(std::launch::async, [] {
        return 6 * 7;
    });

    const int local = 8;
    const int remote = result.get();
    std::cout << local + remote << '\n';
}

Result

50

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources