Introduction to Threads

16 min read

Understanding Threads

When you run a program, the operating system creates a process: an isolated environment with its own memory space, open files, and system resources. Inside that process, the instructions of your code need something to actually execute them line by line. That independent path of execution is called a thread.

By default, a program has a single thread running one instruction after another. If you have a heavy calculation, a network request, or four independent chunks of data to process, a single thread must work through them sequentially. By creating additional threads inside the same process, your program can split work into multiple paths of execution that run concurrently. On a modern multi-core CPU, the operating system can place different threads onto different physical cores so they genuinely execute at the exact same instant (parallelism).

The Main Thread

Every C++ program begins life with one thread already running, created automatically by the operating system before the first line of your code executes. This is the main thread, and its entry point is your main() function.

Every other thread in your program is spawned (directly or indirectly) from this main thread. While the main thread executes code just like any worker thread, it plays a special supervisory role: it typically initializes shared state, launches worker threads, coordinates their results, and determines when the program as a whole finishes.

Creating Threads in C++

Since C++11, threading is built directly into the standard library via the <thread> header. Creating a new thread is as straightforward as constructing a std::thread object with a callable (a regular function, a lambda expression, or a callable object) followed by any arguments you want forwarded to it:

#include <functional>
#include <iostream>
#include <string>
#include <thread>

// 1. Regular free function taking multiple arguments
void processChunk(int id, const std::string& label) {
    std::cout << "Function worker " << id << " processing " << label << "\n";
}

// 3. Callable object (functor): a struct/class that overloads operator()
struct Multiplier {
    int factor;
    void operator()(int id, int input, int& output) const {
        output = input * factor;
        std::cout << "Functor worker " << id << " computed " << output << "\n";
    }
};

int main() {
    // 1. Free function + arguments (copied/moved by value)
    std::thread t1(processChunk, 1, "pixels");

    // 2. Lambda expression + arguments
    std::thread t2([](int id, double scale) {
        std::cout << "Lambda worker " << id << " scaling by " << scale << "\n";
    }, 2, 1.5);

    // 3. Callable object (functor) + passing an argument by reference via std::ref
    int result = 0;
    Multiplier timesTen{10};
    std::thread t3(timesTen, 3, 7, std::ref(result));

    t1.join();  // Wait for t1 to finish
    t2.join();  // Wait for t2 to finish
    t3.join();  // Wait for t3 to finish

    std::cout << "Result from t3: " << result << "\n";  // 70
    return 0;
}

The moment each std::thread is constructed, the OS schedules its callable to run concurrently alongside main().

Info

Why std::ref is required for references: std::thread copies or moves its arguments into internal storage for the new thread by default, even if the target function parameter is a reference (int&). This is an intentional safety choice: passing a local variable by reference to another thread is risky, because if the thread outlives the scope where that variable lives, the worker is left with a dangling reference to destroyed stack memory. Copying by default is safe, and requiring std::ref(variable) (from <functional>, as shown with result above) forces you to explicitly opt in at the call site and take responsibility for keeping that variable alive until the thread finishes.

Running a Thread on a Member Function

Threads are not limited to standalone functions; you can also run a thread directly on a class member function. Because a non-static member function needs an object instance to operate on (its implicit this pointer), you pass both the address of the member function and a pointer (or reference wrapper) to the object, followed by any method arguments:

#include <iostream>
#include <thread>

class ImageProcessor {
public:
    void applyFilter(int passes) {
        std::cout << "Running " << passes << " filter passes\n";
    }
};

int main() {
    ImageProcessor processor;

    // Syntax: std::thread(&ClassName::method, &objectInstance, args...)
    std::thread worker(&ImageProcessor::applyFilter, &processor, 3);
    worker.join();
    return 0;
}
Warning

When passing &processor to a thread, make sure the object outlives the thread. If processor is destroyed while worker is still running, the thread will access invalid memory (a dangling this pointer), leading to undefined behavior or a crash. If ownership needs to be shared safely, hold the object in a std::shared_ptr<ImageProcessor> and pass that instead.

Joining vs. Detaching Threads

Once you construct a std::thread, it becomes joinable, meaning it represents an active thread of execution that your program is responsible for resolving before the std::thread object goes out of scope. You have two choices:

  1. Join it (.join()): The calling thread pauses and blocks until the worker thread finishes its function. Joining guarantees that all of the worker’s work is complete before you read its results or exit main(), and it cleanly releases the thread’s OS resources.
  2. Detach it (.detach()): Detaching severs the link between the C++ std::thread handle object and the underlying OS thread. You can no longer .join() it or wait on it through that handle, and the operating system automatically reclaims its thread resources whenever its function finishes. Importantly, detaching does not disconnect the thread from the process: a detached thread still lives inside your process’s memory space and will still terminate if the process exits or crashes.
std::thread bg([] {
    // Runs independently in the background until finished (or until the process exits)
});
bg.detach();  // The C++ handle no longer owns or tracks the OS thread

When to Detach a Thread

Sometimes you want to launch background work where the caller cannot afford to block on .join(), does not need a return value, and does not want to keep track of a std::thread object. Common real-world use cases include:

  • Fire-and-forget telemetry or logging: Flushing non-critical analytics, audit events, or diagnostic logs over the network in the background where dropping the last event on a sudden shutdown is acceptable.
  • Long-lived background monitors (“daemon” threads): Tasks inside a server or desktop app (such as a periodic heartbeat, a cache-eviction sweeper, or a file-system watcher) designed to run for the entire lifetime of the application until the process shuts down.
  • Responsive UI or network dispatchers: Kicking off an independent, self-contained task (such as opening an independent document window or handling a short-lived incoming request in a simple server) so the main event loop stays immediately responsive.
Warning

Detach with caution. Because you lose control over when a detached thread finishes, it can easily outlive local variables, objects, or even global state being torn down at program shutdown, causing subtle use-after-free crashes. In modern C++, prefer joining threads (or using a thread pool / C++20’s std::jthread, which joins automatically in its destructor) unless you genuinely want fire-and-forget background work with completely self-contained data.

Stopping a Running Thread

A common surprise for newcomers is that C++ provides no .kill() or .stop() method to forcibly terminate a thread from the outside.

This is deliberate. If you violently kill a thread mid-execution (using low-level OS APIs like TerminateThread), its stack is never unwound: destructors never run, heap allocations leak, files remain half-written, and worst of all, any std::mutex that thread was holding stays locked forever, deadlocking the rest of your program.

Instead, threads are stopped cooperatively: the main thread sets a flag asking the worker to stop, and the worker checks that flag periodically and exits cleanly on its own.

In C++11–17, this is commonly done with a std::atomic<bool>:

#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>

int main() {
    std::atomic<bool> stopRequested{false};

    std::thread worker([&] {
        while (!stopRequested.load()) {
            // Perform a small chunk of work...
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
        }
        std::cout << "Worker cleaned up and exited safely.\n";
    });

    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    stopRequested.store(true);  // Ask the worker to stop
    worker.join();              // Wait for it to wind down cleanly
}

In C++20, this pattern is built right into std::jthread and std::stop_token, which pass a cancellation token automatically and even request a stop and join for you when the std::jthread goes out of scope:

#include <chrono>
#include <iostream>
#include <thread>

int main() {
    std::jthread worker([](std::stop_token st) {
        while (!st.stop_requested()) {
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
        }
        std::cout << "Stopped cleanly via stop_token.\n";
    });

    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    // worker.request_stop() and worker.join() happen automatically at scope exit
}

Crashes and Unjoined Threads

Because threads are not isolated sandboxes, failures in one thread affect the entire program.

If a Worker Thread Crashes

If a worker thread triggers a fatal hardware fault (such as dereferencing a null pointer or dividing by zero) or throws a C++ exception that is not caught inside that thread, the entire process terminates immediately:

  • For a segmentation fault or access violation, the OS kills the whole process, because the corrupted memory space is shared by every thread.
  • For an uncaught C++ exception escaping a thread’s function, C++ cannot unwind into another thread’s stack, so the runtime calls std::terminate(), aborting the entire program.

If a worker can throw exceptions that you want to handle on the main thread, either catch them inside the worker or use std::async / std::future, which captures exceptions automatically and rethrows them when .get() is called.

If You Don’t Join Threads and main() Exits or Crashes

Two distinct scenarios happen depending on how the main thread ends:

  1. The main program crashes (or calls abort() / terminates abnormally): The operating system immediately tears down the entire process and reclaims its address space. Because every thread (even a detached one) lives inside that process’s memory, every still-running worker thread is killed instantaneously mid-instruction. Their stacks are not unwound, their destructors do not run, and any in-progress work (like unflushed file writes or network transfers) is cut off abruptly.
  2. The main thread finishes normally, but you forgot to call .join() or .detach(): When a still-joinable std::thread object goes out of scope at the end of main(), its destructor explicitly calls std::terminate(), intentionally crashing your program! C++ forces this rule so you can never accidentally abandon a running thread silently.
Tip

Always pair every std::thread with a guaranteed .join() (even along early-return or exception paths), or use C++20’s std::jthread so cleanup happens automatically via RAII.

Interactive Visualization

Now that you know how threads branch off from main(), share the same process timeline, and synchronize at .join(), watch it in action below:

  • Watch the yellow main() thread drop through time, spawn 4 worker threads (t1–t4) via std::thread, and wait (dashed line) until all workers merge back via .join().
  • Play / Pause, Replay, or Shuffle (bar icon) to randomize thread workloads and see which thread becomes the bottleneck.
  • Use βˆ’ / + to change the number of worker threads (1–6), or toggle Parallel / Sequential to compare elapsed wall-clock time on the same scale.
  • Use the Timeline slider at the bottom to scrub to any exact moment (with tick marks for thread spawn and join), and the Speed slider (0.2×–2.0Γ—) to slow down or speed up playback.
  • Drag any worker thread’s end node vertically to change its workload duration and see how it affects .join().

Comments

Clicking this button loads the comment box from giscus.app (powered by GitHub Discussions). See our Privacy Policy.