C++ Multithreading Library
C++11 introduced multithreading support through the library, allowing developers to easily implement parallel processing in programs.
This article will introduce library's basic concepts, definitions, syntax, and how to use it to create and manage threads.
A thread is the smallest unit of program execution and the smallest unit that the operating system can schedule for computation.
In a multithreaded program, multiple threads can execute in parallel, improving the program's execution efficiency.
C++ Library overview
library is part of the C++ standard library, providing basic functions for creating and managing threads; it includes the following key components:
std::thread: Represents a thread; can create, start, wait for, and destroy threads.std::this_thread: Provides some static member functions for operating on the current thread.std::thread::id: The unique identifier of a thread.
Create a thread
To create a thread, you need to instantiate the std::thread class and pass a callable object (function, lambda expression, or member function of an object) as a parameter.
Example
#include
#include
void
print_id
(
int
id
)
{
std
::
cout
<<
"ID: "
<<
id
<<
", Thread ID: "
<<
std
::
this_thread
::
get_id
(
)
<<
std
::
endl
;
}
int
main
(
)
{
std
::
thread
t1
(
print_id,
1
)
;
std
::
thread
t2
(
print_id,
2
)
;
}
Start a thread
creation std::thread object, the thread starts executing immediately; you can call the join() method to wait for the thread to finish.
t1.join();
t2.join();
Wait for the thread to finish
join() method blocks the current thread until the called thread finishes execution.
Destroy a thread
When the thread finishes execution, you can use the detach() method to detach the thread, or let the std::thread object go out of scope and be destroyed automatically.
t1.detach(); // 线程将继续运行,但无法再被 join 或 detach
Example: Using to create parallel computation
Below is an example using library's parallel computation example, computing the sum of two numbers.
Example
#include
#include
int
sum
=
0
;
void
add
(
int
a,
int
b
)
{
sum
=
a
b
;
}
int
main
(
)
{
int
a
=
5
;
int
b
=
10
;
std
::
thread
t1
(
add, a, b
)
;
std
::
thread
t2
(
add, a, b
)
;
t1.
join
(
)
;
t2.
join
(
)
;
std
::
cout
<<
"Sum: "
<<
sum
<<
std
::
endl
;
// Output: Sum: 30
}
The output is:
Sum: 30
In the following example, we will create two threads, each executing a simple function that prints a message and sleeps for a while:
Example
#include
#include
#include
// A simple function executed in a thread
void
print_message
(
const
std
::
string
&
message,
int
delay
)
{
std
::
this_thread
::
sleep_for
(
std
::
chrono
::
milliseconds
(
delay
)
)
;
std
::
cout
<<
message
<<
std
::
endl
;
}
int
main
(
)
{
// Create two threads executing the print_message function
std
::
thread
t1
(
print_message,
"Hello from thread 1"
,
1000
)
;
std
::
thread
t2
(
print_message,
"Hello from thread 2"
,
500
)
;
// Wait for thread t1 to finish
if
(
t1.
joinable
(
)
)
{
t1.
join
(
)
;
}
// Wait for thread t2 to finish
if
(
t2.
joinable
(
)
)
{
t2.
join
(
)
;
}
std
::
cout
<<
"Main thread finished."
<<
std
::
endl
;
return
0
;
}
The output is:
Hello from thread 2
Hello from thread 1
Main thread finished.
Notes
- Thread safety: in a multithreaded environment, shared resources need synchronized access to avoid data races.
- Thread lifecycle: ensure that thread objects are properly handled after execution to avoid resource leaks.
Classes and functions
library contains a series of classes and functions for creating, managing, and synchronizing threads.
Below is a detailed introduction to C++'s library:
Main components
- std::thread
- std::mutex
- std::lock_guard
- std::unique_lock
- std::condition_variable
- std::future and std::promise
- std::async
std::thread
The std::thread class is used to create and manage threads.
Example
#include
#include
void
print_hello
(
)
{
std
::
cout
<<
"Hello from thread!"
<<
std
::
endl
;
}
int
main
(
)
{
std
::
thread
t
(
print_hello
)
;
t.
join
(
)
;
// Wait for thread t to end
return
0
;
}
Important methods
- join(): Wait for the thread to finish.
- detach(): Run the thread in the background, no longer waiting for it to finish.
- joinable(): Check whether the thread can be joined or detached.
std::mutex
The std::mutex class is used to synchronize access to shared resources.
Example
#include
#include
#include
std
::
mutex
mtx
;
// Create a global mutex object
int
shared_resource
=
0
;
// Shared resource
// Thread function
void
increment
(
)
{
std
::
lock_guard
<
std
::
mutex
lock
(
mtx
)
;
// Lock to ensure thread safety
++
shared_resource
;
std
::
cout
<<
"Incremented shared_resource to "
<<
shared_resource
<<
std
::
endl
;
// lock is automatically released when lock_guard leaves scope
}
int
main
(
)
{
std
::
thread
t1
(
increment
)
;
std
::
thread
t2
(
increment
)
;
t1.
join
(
)
;
// Wait for thread t1 to finish
t2.
join
(
)
;
// Wait for thread t2 to finish
std
::
cout
<<
"Final value of shared_resource: "
<<
shared_resource
<<
std
::
endl
;
return
0
;
}
std::lock_guard
std::lock_guard is an RAII-style lock manager used to automatically manage the lock's lifecycle.
Example
#include
#include
#include
std
::
mutex
mtx
;
void
print_thread_id
(
int
id
)
{
std
::
lock_guard
<
std
::
mutex
lock
(
mtx
)
;
std
::
cout
<<
"Thread ID: "
<<
id
<<
std
::
endl
;
}
int
main
(
)
{
std
::
thread
t1
(
print_thread_id,
1
)
;
std
::
thread
t2
(
print_thread_id,
2
)
;
t1.
join
(
)
;
t2.
join
(
)
;
return
0
;
}
std::unique_lock
std::unique_lock provides more flexible lock management than std::lock_guard.
Example
#include
#include
#include
std
::
mutex
mtx
;
void
print_thread_id
(
int
id
)
{
std
::
unique_lock
<
std
::
mutex
lock
(
mtx
)
;
std
::
cout
<<
"Thread ID: "
<<
id
<<
std
::
endl
;
lock.
unlock
(
)
;
// Can manually unlock
// ... other operations
}
int
main
(
)
{
std
::
thread
t1
(
print_thread_id,
1
)
;
std
::
thread
t2
(
print_thread_id,
2
)
;
t1.
join
(
)
;
t2.
join
(
)
;
return
0
;
}
std::condition_variable
std::condition_variable is used for waiting and notification between threads.
Example
#include
#include
#include
#include
std
::
mutex
mtx
;
std
::
condition_variable
cv
;
bool
ready
=
false
;
void
print_id
(
int
id
)
{
std
::
unique_lock
<
std
::
mutex
lock
(
mtx
)
;
cv.
wait
(
lock,
[
]
{
return
ready
;
}
)
;
std
::
cout
<<
"Thread ID: "
<<
id
<<
std
::
endl
;
}
void
set_ready
(
)
{
std
::
unique_lock
<
std
::
mutex
lock
(
mtx
)
;
ready
=
true
;
cv.
notify_all
(
)
;
}
int
main
(
)
{
std
::
thread
t1
(
print_id,
1
)
;
std
::
thread
t2
(
print_id,
2
)
;
std
::
this_thread
::
sleep_for
(
std
::
chrono
::
seconds
(
1
)
)
;
set_ready
(
)
;
t1.
join
(
)
;
t2.
join
(
)
;
return
0
;
}
std::future and std::promise
std::future and std::promise are used for passing results between threads.
Example
#include
#include
#include
void
calculate_square
(
std
::
promise
<
int
&&
p,
int
x
)
{p.
set_value
(
x
x
)
;
}
int
main
(
)
{
std
::
promise
<
int
p;
std
::
future
<
int
f
=p.
get_future
(
)
;
std
::
thread
t
(
calculate_square, std
::
move
(
p
)
,
5
)
;
std
::
cout
<<
"Square: "
<<
f.
get
(
)
<<
std
::
endl
;
t.
join
(
)
;
return
0
;
}
std::async
std::async is used to launch asynchronous tasks and returns a std::future.
Example
#include
#include
int
calculate_square
(
int
x
)
{
return
x
x
;
}
int
main
(
)
{
std
::
future
<
int
result
=
std::
async
(
calculate_square,
5
)
;
std
::
cout
<<
"Square: "
<<
result.
get
(
)
<<
std
::
endl
;
return
0
;
}
C++'s library provides developers with powerful multithreading support. Through this introduction, we should be able to understand the basic concepts of threads and learn how to use library to create and manage threads. In actual development, using multithreading reasonably can significantly improve program performance and responsiveness.