liveBook · Manning

Thread

As explained in C++ Concurrency in Action, Second Edition

A unit of execution within a process that can run independently of other threads.

A thread is a path of execution within a process. Every C++ program begins with a thread running main(). It can launch additional threads, each with its own entry function. Those threads run concurrently with the initial thread and exit when their entry functions return. section 2.1

Threads can separate work that needs to remain responsive from work that takes time. A DVD player, for example, can handle user input in one thread while another reads and plays the DVD. The threads still need to interact when the user presses Pause, but playback code need not repeatedly check for input. section 1.2.1

Listing 1.1. A simple Hello Concurrent World program
#include <iostream>
#include <thread>
void hello()
{
    std::cout<<"Hello Concurrent World\n";
}
int main()
{
    std::thread t(hello);   3
    t.join();
}

In this small C++ program, std::thread t(hello) starts a second thread at hello(), while the initial thread continues in main(). The call to t.join() makes the initial thread wait; without it, main() could finish before the message is printed. section 1.4.1

Choose threads for a clear benefit, not merely because work can be divided:

  • Threads in one process provide a different way to organize concurrent work than separate processes. Separate processes communicate through channels such as pipes or sockets; threads share a process and must account for shared resources. section 1.1.2
  • Launching a thread takes time and requires operating-system resources and stack space. A short task may finish faster if the existing thread performs it directly. section 1.2.3
  • Multiple threads also make code harder to reason about and maintain. Use them when responsiveness, separation of concerns, or a worthwhile performance gain justifies that cost. section 1.2.1 section 1.2.3

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Works through launching a std::thread and waiting with join(), while deferring fuller thread management and shared-data protection.
Examples
Uses a DVD player’s playback and user interface, plus a Hello World program that starts and joins a second thread.
What it assumes
Assumes familiarity with C++ functions and main(), while introducing additional threads and their entry functions from the beginning.
What you can do after
Build it from scratch: launch a C++ thread with an entry function and join it before main() exits.
How it connects
Connects threads to processes, interprocess communication, separation of concerns, and thread pools.

Also explained in

Compare how 12 books explain thread →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.