Concurrency[conc]

Thread Performance Explained: What Really Drives Speed

Abstract

Thread performance is how quickly a program completes work when tasks run concurrently. It depends on choosing a suitable number of threads, keeping tasks large enough to outweigh thread setup costs, and reducing competition for locks and nearby memory. In practice, more threads do not always mean faster results, so benchmark and profile your workload before choosing a thread pool, parallel tools, or another concurrency model.

Ink drawing of textile threads bottling at a padlocked gate, showing tangling and delay marked by a pocket watch.
Figure 1 — Ink drawing of textile threads bottling at a padlocked gate, showing tangling and delay marked by a pocket watch.

Picture four friends sharing one car on a road trip. Adding a fifth passenger doesn’t always get you there faster, especially when everyone is fighting over the same seat.

Threads work the same way: more of them can speed a program up or slow it down, depending on what they’re competing for.

In this post, we’ll cover what really drives thread performance in C++: thread count, creation cost, contention, false sharing, and measurement.

We’ll also look at std::jthread (C++20), thread pools, and parallel algorithms (C++17), plus the profiling tools that show where the time actually goes.

C++ Approaches That Affect Thread Performance

Your tool choice decides whether threads do real work or sit waiting. Here are the common options and their traps.

Easy-to-use parallel tools

Calling std::async with std::launch::async starts the work on a new thread right away. Without a policy, the default is implementation-defined and the call may run deferred, on the calling thread instead.

Consider a game engine programmer whose particle updates run one at a time by default. Passing std::launch::async makes them run side by side.

OpenMP (Open Multi-Processing) adds a parallel for reduction pragma that splits a loop and merges each thread’s partial sum, once you enable it with -fopenmp. Some implementations reuse pooled threads, so you can’t assume each call creates one.

Keeping benchmark code honest and clean

Compilers may delete work whose result nobody reads, so a timing loop can measure nothing. Block that with your benchmark framework’s optimization barrier, not volatile, which doesn’t order threads.

Print a checksum after timing so the work stays observable. Give each thread its own accumulator and combine the totals at the end. Shared counters make threads fight, and the benchmark measures that fight.

Coordinating threads and handling errors

Standard C++ has no channel type, so you build a queue with a mutex and a condition variable. Two threads locking two mutexes in opposite orders can deadlock, and unsynchronized shared data is a data race, which is undefined behavior.

Lock several mutexes together with std::scoped_lock (C++17). Where Go reaches for panic and recover, C++ uses exceptions, and one that escapes a std::thread calls std::terminate, so catch it inside the thread.

Since C++20, std::jthread joins automatically, so a forgotten join no longer ends your program. Less to forget.

Picking How Many Threads to Run

More threads feels like more speed, but past a point they only add overhead, so let’s size them first.

Matching thread count to CPU cores

Start with the hardware_concurrency call in <thread>, which reports how many threads the hardware can run at once. Treat it as an upper limit, not a target. Threads beyond your physical cores rarely add speed for CPU-bound work.

Running more threads than cores, called oversubscription, makes the scheduler switch between them and can degrade performance. Leave one core free for the operating system. And hardware_concurrency may return zero, so guard that case.

When extra threads stop helping

Scaling starts near linear: two threads roughly halve the time, if the work divides cleanly. Then the gains flatten. Find the least number of threads that gets you close to the best time.

Time one workload at 1, 2, 4, and 8 threads, tabulate speedup, and look for the bend. The algorithm matters too: light work per element leaves less to divide, so gains stop sooner. Measure before you commit.

Ink drawing shows a workshop with brass gears and a chart illustrating performance gains, while extra workers stand idle in the background.
Figure 2 — Ink drawing shows a workshop with brass gears and a chart illustrating performance gains, while extra workers stand idle in the background.

The cost of starting new threads

Every thread has a setup cost before your work runs. For tiny tasks, that cost outweighs the work, which is why multithreading isn’t always faster. A thread pool pays it once by reusing workers instead of spawning a thread per task. Starting a thread by hand for each task is the cost a pool takes over.

Picture a build tool maintainer who starts a thread for each small source file. A pool sized to the core count leaves the build compiling, not creating threads.

C++17 added parallel algorithms, but passing std::execution::par to std::sort is a request, not a guarantee: the library may still run serially.

Many implementations rely on a backend such as Intel’s Threading Building Blocks (TBB), which you may need to link.

Why Multithreading Sometimes Fails to Help

Adding threads often doesn’t help, and the cause usually hides in memory layout, locking, or measurement.

When threads fight over nearby memory

Cores move memory in cache lines, and false sharing happens when unrelated variables share a line.

  • Adjacent memory writes. A game engine programmer’s four workers bump neighboring counters that sit on one cache line, forcing constant reloads. They’re waiting, not working.
  • Cache line padding. Pad each counter to fill its own line.
  • Use local accumulators. Sum into a local variable and publish once, not on every pass.
  • Shared memory bottleneck. Threads writing the same variable run one at a time, not in parallel. A mutex over a whole table causes lock contention, while a lock per bucket (finer mutex granularity) lets threads work side by side.
  • hardware_destructive_interference_size (C++17). Declared in <new>, it gives a minimum offset between objects that avoids false sharing. Pair it with alignas.

How platforms and compilers change results

Four factors skew results:

  • Windows vs Linux timings. Each OS schedules threads differently, so compare results only within one platform.
  • Optimization flags effect. Flags change timings a lot, so match them across runs.
  • Compiler removing loops. An unused result can let the optimizer delete the loop. Write the result to a volatile variable.
  • -march=native option. It uses every instruction your build machine supports, so the binary can fail on older hardware. Target the oldest hardware you deploy to instead.

Common timing mistakes to avoid

  • Console I/O in timed region. Printing inside the timer measures the terminal. Print after you stop the clock.
  • std::clock measures CPU time. That’s processor time, so a thread blocked on a mutex doesn’t count.
  • Prefer steady_clock. It measures elapsed time and ignores system clock changes.
  • Time only the work. Keep setup and thread creation out of the timed block.

Once your timer is trustworthy, profile where threads wait with perf on Linux, Intel VTune Profiler, or ThreadSanitizer (TSan) for data races.

Vintage stopwatch focuses on a polished gear, while distractions like a printer and idle worker sit outside the frame.
Figure 3 — Vintage stopwatch focuses on a polished gear, while distractions like a printer and idle worker sit outside the frame.

Comparing Goroutines and OS Threads

Goroutines and C++ threads both run work concurrently, but they differ in weight and in how the runtime or the kernel schedules that work onto operating system (OS) threads.

How Go goroutines stay lightweight

A goroutine is a lightweight, user-space thread managed by the Go runtime. Each starts with a stack of about 2KB.

A Communications of the ACM article, from the Association for Computing Machinery, notes that goroutines “start with only a few kilobytes of stack, which is resized as needed, without programmer involvement.”

Goroutines are multiplexed onto a shared set of OS threads, and the runtime decides when each one runs.

How C++ threads map to the OS

A std::thread is a thin wrapper over a native operating-system thread, which reserves about 1MB of stack. You create and manage each one yourself, and threads communicate through shared memory guarded by mutexes or atomics. You own every thread.

Consider a C++ developer who opens one std::thread per incoming connection. Each reserves about 1MB, so the server’s footprint grows with every connection, and the question becomes which threads to keep, not how many to start.

A thread pool answers that, and we’ll cover one later.

How each scheduler decides what runs

The real difference is who decides what runs. Go uses M:N scheduling, placing goroutines (G) on OS threads (M) through logical processors (P). An idle processor can steal queued work from a busy one, which is work-stealing across cores.

C++ takes the simpler route with 1:1 threading: each std::thread is one OS thread, scheduled by the kernel. The trade-off is predictability: the OS scheduler is one general-purpose policy, and you don’t have to learn a second scheduler on top of it.

Resource Use and How to Benchmark It

Every thread costs memory and scheduler time before doing any work. Here’s how to measure that on your machine.

What memory and context switches cost

As A Comparison of Scalable Multi-Threaded Stack Mechanisms notes, thread count is capped by stack memory and operating-system limits. The squeeze grows with the count, since there is “less stack space available per thread.”

Compare your stack size against your deepest call chain.

Find your practical ceiling by launching threads in steps until creation fails or the machine slows. Measure it, don’t guess it.

A context switch is the processor swapping one thread for another. A kernel switch needs the operating system to step in, while a user-space switch happens inside your own program.

A game engine programmer splitting a frame into small jobs times both designs on one scene and ships the one with the lower frame time.

An engineer times memory block stacking while two panels contrast fast data transfer with slow, gated processing.
Figure 4 — An engineer times memory block stacking while two panels contrast fast data transfer with slow, gated processing.

Stress tests with simulated workloads

Run each test at rising thread counts. A sleep-bound test has threads wait, the way a server waits on input/output (I/O). A prime test keeps the central processing unit (CPU) busy, making it CPU-bound. Log memory, CPU use and completion time for each run. Work whose speed is set by data access rather than arithmetic is memory bound.

Then raise the count until threads crash or creation fails, and note the limit you hit.

Real-world cases compared side by side

  • Web server, 10,000 connections. Compare a thread per connection with a small fixed pool, and see which one your server can afford.
  • Data processing pipeline. Time each stage on its own thread, then on a shared pool, and watch where work waits.
  • Boost.Asio comparison. Run the same workload on a Boost.Asio version, a C++ library for asynchronous I/O, and on your thread-per-connection code.
  • Code complexity. Count the locks and shared variables in each version, and ask which a reviewer can read in one sitting.

Which Model Fits Your Project

Goroutines and C++ threads both run work concurrently, but they trade off differently, so we’ll match the model to your workload.

When goroutines are the right choice

  • Many concurrent operations. A backend developer running a chat gateway can give each connection its own goroutine and keep every handler plain and sequential.
  • I/O-bound workloads. When a goroutine waits on input/output (I/O), the runtime parks it and frees its operating system (OS) thread.
  • Microservices. Small services that mostly relay requests stay short and easy to review.
  • Resource-constrained deployments. Each goroutine starts with a small stack that grows on demand, so many tasks fit a modest memory budget.

When C++ threads are the better pick

The question is control, not thread count.

  • Precise control needs. std::jthread (C++20) joins on destruction and carries a stop token, so workers can finish cleanly.
  • Compute-intensive workloads. C++17 parallel algorithms, such as std::for_each with std::execution::par, split loops across threads.
  • Low-level hardware. Embedded firmware and game engines need control over memory layout and cache-line placement.
  • Deterministic performance. C++ has no garbage collector pausing your threads, so latency is easier to measure.

A game engine programmer times every frame on her own worker pool, so a slowdown shows up before players feel it. Measure before you commit.

Where concurrency is heading next

  • C++20 coroutines. Coroutines let a function suspend and resume with co_await, which suits code that waits a lot.
  • Senders and receivers. They’re slated for C++26 as a standard way to describe asynchronous work.
  • Go scheduler refinements. The Go runtime keeps tuning how goroutines map onto OS threads, so re-measure after you upgrade.
  • Hardware concurrency features. std::thread::hardware_concurrency() (C++11) reports the hardware thread count, a sensible starting point for pool size.

Here’s the short version: thread performance depends on the work each thread does and what it shares with the others. Match your thread count to your hardware, keep threads from fighting over the same cache lines, and measure before you change anything.

Reach for std::jthread (C++20) when you want automatic joining and cooperative stop requests, and for parallel algorithms (C++17) when your work is already a loop.

Profilers and benchmarks turn guesses into facts, so every change you make is one you can defend in review. Fast threads come from measured choices, not from simply adding more of them.

References

  1. ACM: Digital Library: Communications of the ACM — dl.acm.org
  2. A Comparison of Scalable Multi-Threaded Stack Mechanisms — doi.org (2010)

Read next

  1. std::thread and std::jthread: start, join and stop a threadConcurrency · Miriam Castellanos · written for C++20
  2. Non-Uniform Memory Access Explained, With Tuning TipsConcurrency · Miriam Castellanos
  3. Memory Bound Code: Why Data Access Limits SpeedConcurrency · Miriam Castellanos