The C++ standard library
In multithreaded programming, ensuring data consistency and thread safety is crucial.
The C++ standard library provides a rich set of synchronization primitives for controlling access to shared resources.
The C++ standard library's The header provides a set of tools for implementing synchronization and mutual exclusion between threads in multithreaded programs.
The header was introduced in C++11 and contains classes and functions for mutexes. A mutex is a synchronization mechanism used to prevent multiple threads from accessing a shared resource simultaneously.
A mutex is a synchronization primitive used to control access to a shared resource. When a thread needs to access a shared resource, it tries to lock the mutex. If the mutex is already locked by another thread, the requesting thread will be blocked until the mutex is released.
Basic Syntax
In C++, The header provides the following main classes:
std::mutex: Basic mutex.std::recursive_mutex: Recursive mutex, allowing the same thread to lock it multiple times.std::timed_mutex: Mutex with timeout capability.std::recursive_timed_mutex: Recursive mutex with timeout capability.
Example
1. Using std::mutex
Here is a simple example showing how to use std::mutex to synchronize access to shared resources.
Example
#include
#include
#include
std
::
mutex
mtx
;
// Global mutex
int
shared_resource
=
0
;
void
increment
(
)
{
for
(
int
i
=
0
;
i
<
10000
;
++
i
)
{
mtx.
lock
(
)
;
// Lock the mutex
++
shared_resource
;
mtx.
unlock
(
)
;
// Unlock the mutex
}
}
int
main
(
)
{
std
::
thread
t1
(
increment
)
;
std
::
thread
t2
(
increment
)
;
t1.
join
(
)
;
t2.
join
(
)
;
std
::
cout
<<
"Final value of shared_resource: "
<<
shared_resource
<<
std
::
endl
;
return
0
;
}
Output result:
Final value of shared_resource: 20000
2. Using std::recursive_mutex
A recursive mutex allows the same thread to lock the same mutex multiple times. Here is an example using std::recursive_mutex .
Example
#include
#include
#include
std
::
recursive_mutex
rmtx
;
// Create a recursive mutex object
int
shared_resource
=
0
;
// Shared resource
// Recursive function
void
recursive_increment
(
int
count
)
{
if
(
count
<=
0
)
return
;
std
::
lock_guard
<
std
::
recursive_mutex
lock
(
rmtx
)
;
// Lock to ensure thread safety
++
shared_resource
;
std
::
cout
<<
"Incremented shared_resource to "
<<
shared_resource
<<
" (count = "
<<
count
<<
")"
<<
std
::
endl
;
// Recursive call
recursive_increment
(
count
1
)
;
}
int
main
(
)
{
std
::
thread
t1
(
recursive_increment,
3
)
;
// Thread t1 executes recursive_increment(3)
std
::
thread
t2
(
recursive_increment,
3
)
;
// Thread t2 executes recursive_increment(3)
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
;
}
Output result:
Incremented shared_resource to 1 (count = 3)
Incremented shared_resource to 2 (count = 2)
Incremented shared_resource to 3 (count = 1)
Incremented shared_resource to 4 (count = 0)
Incremented shared_resource to 5 (count = 3)
Incremented shared_resource to 6 (count = 2)
Incremented shared_resource to 7 (count = 1)
Incremented shared_resource to 8 (count = 0)
Final value of shared_resource: 8
Code analysis:
-
creation
std::recursive_mutexobject:std::recursive_mutex rmtx;is a recursive mutex that allows the same thread to acquire the lock multiple times. -
Shared resource:
int shared_resource = 0;is a resource accessed jointly by multiple threads. -
Recursive function
recursive_increment:
std::lock_guard locks rmtx . Because a recursive mutex is used, the same thread can acquire the lock multiple times.++shared_resource Increments the value of the shared resource.-
Create and run threads:
std::thread t1(recursive_increment, 3); and std::thread t2(recursive_increment, 3); creates two threads respectively, both executing recursive_increment(3).t1.join() and t2.join() waits for both threads to finish.Notes
- Ensure that you unlock the mutex after each lock to avoid deadlock.
- Use
std::lock_guardorstd::unique_lockcan automatically manage the locking and unlocking of the mutex, reducing the chance of errors. - Avoid calling functions that may throw exceptions while holding the mutex, as this may cause a deadlock.
is a very important header in the C++ standard library; it provides basic synchronization mechanisms for multithreaded programming. By using mutexes, we can ensure that access to shared resources is safe, thereby avoiding data races and inconsistency issues.
More details
1. std::mutex
provides a basic mutex, ensuring that only one thread can access the shared resource at a time.
Example
#include
std
::
mutex
mtx
;
void
thread_function
(
)
{
std
::
lock_guard
<
std
::
mutex
lock
(
mtx
)
;
// Access the shared resource
}
2. std::recursive_mutex
allows the same thread to acquire the lock multiple times without causing a deadlock, which is especially useful for recursive functions.
Example
#include
std
::
recursive_mutex
rmtx
;
void
recursive_function
(
int
count
)
{
if
(
count
<=
0
)
return
;
std
::
lock_guard
<
std
::
recursive_mutex
lock
(
rmtx
)
;
// Recursive call
recursive_function
(
count
1
)
;
}
3. std::timed_mutex
provides a timed mutex, allowing a timeout to be set when attempting to acquire the lock.
Example
#include
#include
std
::
timed_mutex
tm
;
void
try_lock_for_example
(
)
{
if
(
tm
.
try_lock_for
(
std
::
chrono
::
seconds
(
1
)
)
)
{
// Successfully acquired the lock
tm
.
unlock
(
)
;
}
else
{
// Failed to acquire the lock
}
}
4. std::recursive_timed_mutex
inherits from std::timed_mutex, allowing the same thread to acquire the lock multiple times while supporting timed functionality.
Example
#include
#include
std
::
recursive_timed_mutex
rtm
;
void
recursive_timed_function
(
int
count
)
{
if
(
count
<=
0
)
return
;
if
(
rtm.
try_lock_for
(
std
::
chrono
::
seconds
(
1
)
)
)
{
// Successfully acquired the lock
recursive_timed_function
(
count
1
)
;
rtm.
unlock
(
)
;
}
else
{
// Failed to acquire the lock
}
}
5. std::lock_guard
a wrapper that automatically manages a std::mutex lock, using RAII style to ensure the lock is automatically released at the end of the scope.
Example
#include
std
::
mutex
mtx
;
void
function
(
)
{
std
::
lock_guard
<
std
::
mutex
lock
(
mtx
)
;
// Access the shared resource
}
6. std::unique_lock
provides more flexible lock management than std::lock_guard; it can manually release and reacquire the lock, and also supports timed locking.
Example
#include
#include
std
::
mutex
mtx
;
void
function
(
)
{
std
::
unique_lock
<
std
::
mutex
lock
(
mtx
)
;
// Access the shared resource
// Can manually release the lock
lock.
unlock
(
)
;
// Can reacquire the lock
lock.
lock
(
)
;
// Can perform timed locking
if
(
lock.
try_lock_for
(
std
::
chrono
::
seconds
(
1
)
)
)
{
// Successfully acquired the lock
}
}
7. std::adopt_lock_t
flag type, used to specify that std::unique_lock adopts an existing lock.
Example
std
::
mutex
mtx
;
std
::
unique_lock
<
std
::
mutex
lock
(
mtx, std
::
adopt_lock
)
;
8. std::defer_lock_t
Function: flag type, used to defer locking; no lock is acquired at initialization.
Example
std
::
mutex
mtx
;
std
::
unique_lock
<
std
::
mutex
lock
(
mtx, std
::
defer_lock
)
;
// Can call lock.lock() at some later moment
9. std::try_to_lock_t
flag type, used to attempt locking without blocking.
Example
std
::
mutex
mtx1, mtx2
;
std
::
unique_lock
<
std
::
mutex
lock1
(
mtx1, std
::
try_to_lock
)
;
std
::
unique_lock
<
std
::
mutex
lock2
(
mtx2, std
::
try_to_lock
)
;
if
(
lock1
&&
lock2
)
{
// Successfully acquired both locks
}