codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚡

C++ Programming

61 / 87 topics
55C++11 Features56Preprocessors and Macros57Templates (Function & Class Templates)58Namespaces59File Handling, Buffers, istream & ostream60Exception Handling, Asserts & Debugging61Multithreading
Tutorials/C++ Programming/Multithreading
⚡C++ Programming

Multithreading

Updated 2026-05-12
30 min read

Multithreading

Multithreading is a powerful feature of modern programming that allows multiple threads to run concurrently within a single process. This can significantly enhance the performance and responsiveness of applications, especially those performing CPU-intensive tasks or I/O operations. In C++, multithreading is facilitated by the <thread> library, which provides a high-level interface for creating and managing threads.

In this tutorial, we will explore various aspects of multithreading in C++ using the std::thread class. We'll cover thread creation, synchronization mechanisms like mutexes and condition variables, atomic operations, and asynchronous programming with futures. By the end of this tutorial, you'll have a solid understanding of how to implement multithreaded applications in C++.

Introduction

Multithreading allows multiple threads of execution to run concurrently within a single process. This can lead to significant performance improvements by utilizing multiple CPU cores or by performing I/O operations while waiting for other tasks to complete. In C++, the std::thread class provides a simple and efficient way to create and manage threads.

Core Content

10.1 Creating Threads with std::thread

The std::thread class is used to create and manage threads in C++. A thread can be created by passing a function or callable object to the constructor of std::thread.

Example: Basic Thread Creation

C++
1#include <iostream>
2#include <thread>
3
4void printHello() {
5 std::cout << "Hello from thread!" << std::endl;
6}
7
8int main() {
9 std::thread t(printHello);
10 t.join();
11 return 0;
12}
Output

In this example, the printNumbers function is executed by a thread. The main function waits for the thread to complete using t.join().

Detaching Threads

The detach() method allows the thread to run independently of the creating thread. Once detached, the thread's resources are managed automatically when it finishes execution.

C++
1#include <iostream>
2#include <thread>
3
4void printNumbers(int n) {
5 for (int i = 0; i < n; ++i) {
6 std::cout << i << " ";
7 }
8}
9
10int main() {
11 std::thread t(printNumbers, 5);
12 t.detach();
13 // The main function continues execution without waiting for the thread
14 return 0;
15}
Output

In this example, a mutex mtx is used to protect the critical section where numbers are printed. The std::lock_guard class is used to automatically acquire and release the mutex.

Condition Variables

A condition variable allows threads to wait for certain conditions to be met before proceeding.

C++
1#include <iostream>
2#include <thread>
3#include <mutex>
4#include <condition_variable>
5
6std::mutex mtx;
7std::condition_variable cv;
8bool ready = false;
9
10void worker() {
11 std::unique_lock<std::mutex> lock(mtx);
12 cv.wait(lock, []{ return ready; });
13 std::cout << "Worker thread is processing" << std::endl;
14}
15
16int main() {
17 std::thread t(worker);
18 std::this_thread::sleep_for(std::chrono::seconds(1));
19 {
20 std::lock_guard<std::mutex> lock(mtx);
21 ready = true;
22 }
23 cv.notify_one();
24 t.join();
25 return 0;
26}
Output

In this example, an atomic integer counter is used to ensure that the increment operation is performed atomically.

10.5 Asynchronous Programming with async and future

The &lt;future&gt; library provides facilities for asynchronous programming, allowing tasks to be executed in separate threads and their results to be retrieved later.

C++
1#include <iostream>
2#include <future>
3
4int computeSum(int a, int b) {
5 return a + b;
6}
7
8int main() {
9 std::future<int> result = std::async(std::launch::async, computeSum, 5, 3);
10 std::cout << "Computing sum..." << std::endl;
11 std::cout << "Result: " << result.get() << std::endl;
12 return 0;
13}
Output

In this example, the program calculates the sum of numbers from 1 to 1,000,000 using four threads. Each thread calculates a portion of the sum and stores the result in a shared vector. The main function waits for all threads to complete using join() and then sums up the results.

Summary

ConceptDescription
std::threadClass for creating and managing threads.
join()Waits for a thread to finish execution.
detach()Allows a thread to run independently.
MutexSynchronization primitive to protect critical sections.
std::lock_guardRAII-style mutex management.
Condition VariableAllows threads to wait for certain conditions.
Atomic OperationsEnsure atomicity of operations.
std::asyncExecutes a function asynchronously and returns a future.
future.get()Retrieves the result of an asynchronous computation.

What's Next?

In the next tutorial, we will explore the Standard Template Library (STL) and its various containers such as vectors, lists, and maps. These containers provide efficient data structures for storing and manipulating collections of elements.

Stay tuned for more advanced C++ concepts!


PreviousException Handling, Asserts & DebuggingNext Introduction to STL & Containers

Recommended Gear

Exception Handling, Asserts & DebuggingIntroduction to STL & Containers