C++ Multithreading
A thread is a lightweight unit of execution in a program that allows the program to perform multiple tasks simultaneously.
Multithreading is a special form of multitasking; multitasking allows a computer to run two or more programs at the same time.
Generally, there are two types of multitasking:Process-based and thread-based.
- Process-based multitasking is the concurrent execution of programs.
- Thread-based multitasking is the concurrent execution of fragments of the same program.

C++ multithreaded programming involves creating and managing multiple concurrently executing threads within a single program.
C++ provides powerful multithreading support, especially since the C++11 standard and later, through the standard library makes multithreaded programming simpler and safer.
Concept explanation
Thread
- A thread is a single sequential control flow in program execution; multiple threads can run independently within the same process.
- Threads share the process's address space, file descriptors, heap, and global variables, but each thread has its own stack, registers, and program counter.
Concurrency and Parallelism
- Concurrency: Multiple tasks alternate execution within time slices, showing the effect of simultaneous execution.
- Parallelism: Multiple tasks execute simultaneously on multiple processors or processor cores.
The C++11 and later standards provide multithreading support; the core components include:
std::thread: Used to create and manage threads.std::mutex: Used for mutual exclusion between threads, preventing multiple threads from accessing shared resources simultaneously.std::lock_guardandstd::unique_lock: Used to manage the acquisition and release of locks.std::condition_variable: Used for condition variables between threads, coordinating waiting and notification between threads.std::futureandstd::promise: Used to implement value passing and task synchronization between threads.
Create a thread
After C++11, the new standard thread library std::thread was added; std::thread in
**Note:** some earlier compilers used the C++11 compile flag -std=c++11:
g++ -std=c++11 test.cpp
std::thread
#include
std::thread thread_object(callable, args...);
callable: Callable object, which can be a function pointer, function object, Lambda expression, etc.args...: Passed tocallable's parameter list.
Using a function pointer
Creating a thread via a function pointer is the most basic way:
Example
#include
#include
void
printMessage
(
int
count
)
{
for
(
int
i
=
0
;
i
<
count
;
++
i
)
{
std
::
cout
<<
"Hello from thread (function pointer)!\n"
;
}
}
int
main
(
)
{
std
::
thread
t1
(
printMessage,
5
)
;
// Create a thread, passing a function pointer and arguments
t1.
join
(
)
;
// Wait for the thread to finish
return
0
;
}
After compiling with g++ -std=c++11, the execution output is:
Hello from thread (function pointer)!
Hello from thread (function pointer)!
Hello from thread (function pointer)!
Hello from thread (function pointer)!
Hello from thread (function pointer)!
Using a function object
via the in the class operator() method to define a function object to create a thread:
Example
#include
#include
class
PrintTask
{
public
:
void
operator
(
)
(
int
count
)
const
{
for
(
int
i
=
0
;
i
<
count
;
++
i
)
{
std
::
cout
<<
"Hello from thread (function object)!\n"
;
}
}
}
;
int
main
(
)
{
std
::
thread
t2
(
PrintTask
(
)
,
5
)
;
// Create a thread, passing a function object and arguments
t2.
join
(
)
;
// Wait for the thread to finish
return
0
;
}
After compiling with g++ -std=c++11, the execution output is:
Hello from thread (function object)!
Hello from thread (function object)!
Hello from thread (function object)!
Hello from thread (function object)!
Hello from thread (function object)!
Using a Lambda expression
A Lambda expression can directly define inline the code executed by the thread:
Example
#include
#include
int
main
(
)
{
std
::
thread
t3
(
[
]
(
int
count
)
{
for
(
int
i
=
0
;
i
<
count
;
++
i
)
{
std
::
cout
<<
"Hello from thread (lambda)!\n"
;
}
}
,
5
)
;
// Create a thread, passing a Lambda expression and arguments
t3.
join
(
)
;
// Wait for the thread to finish
return
0
;
}
After compiling with g++ -std=c++11, the execution output is:
Hello from thread (lambda)!
Hello from thread (lambda)!
Hello from thread (lambda)!
Hello from thread (lambda)!
Hello from thread (lambda)!
Thread management
join()
join() is used to wait for the thread to finish execution. If you destroy the thread object directly without calling join() or detach(), it will cause the program to crash.
t.join();
detach()
detach() separates the thread from the main thread; the thread runs independently in the background, and the main thread no longer waits for it.
t.detach();
Passing arguments to threads
Pass by value
Arguments can be passed to a thread by value:
std::thread t(func, arg1, arg2);
Pass by reference
If you need to pass a reference argument, you need to use std::ref:
Example
#include
#include
void
increment
(
int
&
x
)
{
++
x
;
}
int
main
(
)
{
int
num
=
0
;
std
::
thread
t
(
increment, std
::
ref
(
num
)
)
;
// Use std::ref to pass a reference
t.
join
(
)
;
std
::
cout
<<
"Value after increment: "
<<
num
<<
std
::
endl
;
return
0
;
}
Comprehensive example
Here is a complete example showing how to use the above three ways to create threads and manage them.
Example
#include
#include
using
namespace
std
;
// A simple function used as the thread's entry function
void
foo
(
int
Z
)
{
for
(
int
i
=
0
;
i
<
Z
;
i
++
)
{
cout
<<
"Thread uses function pointer as callable argument\n"
;
}
}
// Callable object class definition
class
ThreadObj
{
public
:
void
operator
(
)
(
int
x
)
const
{
for
(
int
i
=
0
;
i
<
x
;
i
++
)
{
cout
<<
"Thread uses function object as callable argument\n"
;
}
}
}
;
int
main
(
)
{
cout
<<
"Threads 1, 2, 3 run independently"
<<
endl
;
// Create a thread using a function pointer
thread th1
(
foo,
3
)
;
// Create a thread using a function object
thread th2
(
ThreadObj
(
)
,
3
)
;
// Create a thread using a Lambda expression
thread th3
(
[
]
(
int
x
)
{
for
(
int
i
=
0
;
i
<
x
;
i
++
)
{
cout
<<
"Thread uses lambda expression as callable argument\n"
;
}
}
,
3
)
;
// Wait for all threads to finish
th1.
join
(
)
;
// Wait for thread th1 to finish
th2.
join
(
)
;
// Wait for thread th2 to finish
th3.
join
(
)
;
// Wait for thread th3 to finish
return
0
;
}
Using the C++11 compile flag -std=c++11:
g++ -std=c++11 test.cpp
The output of the above code may differ across platforms or each run, because the execution order of threads is determined by the operating system's scheduling algorithm; multiple threads run concurrently and output may be interleaved, for example:
线程 1 、2 、3 独立运行
线程使用函数指针作为可调用参数
线程使用函数对象作为可调用参数
线程使用 lambda 表达式作为可调用参数
线程使用函数指针作为可调用参数
...
Thread synchronization and mutual exclusion
In multithreaded programming, thread synchronization and mutual exclusion are two very important concepts; they are used to control multiple threads' access to shared resources to avoid data races, deadlocks, and other problems.
1. Mutex
A mutex is a synchronization primitive used to prevent multiple threads from accessing a shared resource simultaneously. When a thread needs to access a shared resource, it must first lock the mutex. If the mutex is already locked by another thread, the requesting thread will be blocked until the mutex is unlocked.
std::mutex: used to protect shared resources and prevent data races.
std::mutex mtx;
mtx.lock(); // 锁定互斥锁
// Access shared resource
mtx.unlock(); // 释放互斥锁
std::lock_guard and std::unique_lock: automatically manage the acquisition and release of locks.
std::lock_guard lock(mtx); // 自动锁定和解锁
// Access shared resource
Example of using a mutex:
Example
#include
std
::
mutex
mtx
;
// Global mutex
void
safeFunction
(
)
{
mtx.
lock
(
)
;
// Request to lock the mutex
// Access or modify the shared resource
mtx.
unlock
(
)
;
// Release the mutex
}
int
main
(
)
{
std
::
thread
t1
(
safeFunction
)
;
std
::
thread
t2
(
safeFunction
)
;
t1.
join
(
)
;
t2.
join
(
)
;
return
0
;
}
2. Locks
C++ provides various lock types to simplify the use and management of mutexes.
Common lock types include:
- std::lock_guard: a scope lock that automatically locks the mutex when constructed and unlocks it when destructed.
- std::unique_lock: similar to std::lock_guard, but provides more flexibility, such as being able to transfer ownership and manually unlock.
Example of using a lock:
Example
#include
std
::
mutex
mtx
;
void
safeFunctionWithLockGuard
(
)
{
std
::
lock_guard
<
std
::
mutex
lk
(
mtx
)
;
// Access or modify the shared resource
}
void
safeFunctionWithUniqueLock
(
)
{
std
::
unique_lock
<
std
::
mutex
ul
(
mtx
)
;
// Access or modify the shared resource
// ul.unlock(); // Optional: manually unlock
// ...
}
3. Condition Variable
A condition variable is used for coordination between threads, allowing one or more threads to wait for a condition to occur. It is usually used together with a mutex to achieve synchronization between threads.
std::condition_variable is used to implement the wait and notification mechanism between threads.
std::condition_variable cv;
std::mutex mtx;
bool ready = false;
std::unique_lock lock(mtx);
cv.wait(lock, []{ return ready; }); // 等待条件满足
// execute after condition is met
Example of using a condition variable:
Example
#include
#include
std
::
mutex
mtx
;
std
::
condition_variable
cv
;
bool
ready
=
false
;
void
workerThread
(
)
{
std
::
unique_lock
<
std
::
mutex
lk
(
mtx
)
;
cv.
wait
(
lk,
[
]
{
return
ready
;
}
)
;
// Wait for condition
// Perform work when the condition is satisfied
}
void
mainThread
(
)
{
{
std
::
lock_guard
<
std
::
mutex
lk
(
mtx
)
;
// Prepare data
ready
=
true
;
}
// Unlock when leaving scope
cv.
notify_one
(
)
;
// Notify one waiting thread
}
4. Atomic Operations
Atomic operations ensure that access to shared data is indivisible; that is, in a multithreaded environment, an atomic operation either fully executes or does not execute at all, with no intermediate state.
Example of using atomic operations:
Example
#include
#include
std
::
atomic
<
int
count
(
0
);
void
increment
(
)
{
count.
fetch_add
(
1
, std
::
memory_order_relaxed
)
;
}
int
main
(
)
{
std
::
thread
t1
(
increment
)
;
std
::
thread
t2
(
increment
)
;
t1.
join
(
)
;
t2.
join
(
)
;
return
count
;
// Should return 2
}
5. Thread Local Storage (TLS)
Thread local storage allows each thread to have its own copy of data. This can be achieved via the thread_local keyword, avoiding contention for shared resources.
Example of using thread local storage:
Example
#include
#include
thread_local
int
threadData
=
0
;
void
threadFunction
(
)
{
threadData
=
42
;
// Each thread has its own threadData copy
std
::
cout
<<
"Thread data: "
<<
threadData
<<
std
::
endl
;
}
int
main
(
)
{
std
::
thread
t1
(
threadFunction
)
;
std
::
thread
t2
(
threadFunction
)
;
t1.
join
(
)
;
t2.
join
(
)
;
return
0
;
}
6. Deadlock and avoidance strategies
A deadlock occurs when multiple threads wait for each other to release resources, but none can continue executing. Strategies to avoid deadlock include:
- Always request resources in the same order.
- Use timeouts to attempt to acquire resources.
- Use a deadlock detection algorithm.
Inter-thread communication
std::future and std::promise: implement value passing between threads.
Example
std
::
promise
<
int
p;
std
::
future
<
int
f
=p.
get_future
(
)
;
std
::
thread
t
(
[
&
p
]
{
p.
set_value
(
10
)
;
// Set the value, triggering the future
}
)
;
int
result
=
f.
get
(
)
;
// Get the value
A message queue (based on std::queue and std::mutex) implements simple inter-thread communication.
C++17 introduced the parallel algorithm library (), some of whose algorithms support parallel execution and can leverage multi-core CPUs for better performance.
Example
#include
#include
#include
std
::
vector
<
int
vec
=
{
1
,
2
,
3
,
4
,
5
};
std
::
for_each
(
std
::
execution
::
par
, vec.
begin
(
)
, vec.
end
(
)
,
[
]
(
int
&
n
)
{
n
=
2
;
}
)
;
Parallel algorithms in the C++ standard library
For more examples, see:
C++ Multithreading: http://www.runoob.com/w3cnote/cpp-multithread-demo.html
C++ std::thread: https://www.runoob.com/w3cnote/cpp-std-thread.html