parts/4.8.Concurrency.md

4.8 Concurrency

C++ includes concurrency within the language, expressed by threads and tasks. Threads are sequences of execution that can be executed concurrently with the entity (thread) that created them, and with each other. There are good reasons to use threads in a C++ program:

  1. The running program, or a running thread, block for real-world events, such as awaiting input, awaiting completion of a system-level event, or communications with non-local systems.

  2. Threading permit other parts of the program to continue execution even while one or more parts are blocked, or lets a program to await and respond to sets of events in the order that they are received.

  3. Threading lets the program make effective use of multiple cores, proving significantly more computing power to a program.

Threads are initiated by calling std::threads constructor. TODO: more from 6.59

A thread in C++ runs until completion, either a normal completion or as the result of an unhandled exception. There is no mechanism in the language to terminate another thread.

C++ threads use a fork-join model. This means that the initiating thread will wait for the completion of the initiated thread at the join place; otherwise the initiating thread will have no indication of when the created thread completes.

The thread is then initialized and begins execution on its sequence of instructions. A thread can be joined, i.e. the joining thread awaits the completion of the joined thread, or a thread can be detached.

Threads share data and events via atomic variables, condition_variables, futures, and mutexes.

Threads terminate when they complete the execution of the function that was named at thread initiation.

C++ also has the notion of light weight concurrency in the form of tasks. These tasks are created by calling the std:packaged_task with a function, lambda expression, bind expression or another function object. It is expected that the results of a task execution is collected at the end of that execution by calling get_future (t) and waiting for that/those completion(s).

In addition, C++ programs can interact with other programs executing in a system using operating system-level calls to initiate, schedule, communicate and destroy/terminate itself or others.

There are a number of significant vulnerabilities associated with concurrency, which are described in clause 6.59 through 6.63 of this document.