C++ lock_guard: Simplify Mutex Management for Thread Synchronization
The 'lock_guard' is a class template in C++ that offers a convenient way to automatically acquire and release a mutex. It's part of the C++11 standard library and is defined in the '
'lock_guard' acts as a simple wrapper around a mutex, locking it during its construction and unlocking it in its destructor. This guarantees that the mutex remains locked while the 'lock_guard' is within scope and is automatically released when it goes out of scope.
Here's an example demonstrating the use of 'lock_guard' to protect a shared resource:
#include <mutex>
#include <iostream>
std::mutex mtx; // global mutex
void print(char ch) {
std::lock_guard<std::mutex> guard(mtx); // acquire the mutex
for (int i = 0; i < 5; ++i) {
std::cout << ch;
}
std::cout << std::endl;
} // release the mutex when guard goes out of scope
int main() {
std::thread t1(print, '*');
std::thread t2(print, '#');
t1.join();
t2.join();
return 0;
}
In this example, the 'print' function is safeguarded by a 'lock_guard' that locks the 'mtx' mutex when the function is called and unlocks it upon function return. This ensures that the two threads calling 'print' don't interfere with each other, resulting in properly synchronized output.
In conclusion, 'lock_guard' proves to be a valuable tool for managing mutexes in C++. It simplifies code that needs to protect shared resources, promoting efficient and reliable multithreading.
原文地址: https://www.cveoy.top/t/topic/mUU8 著作权归作者所有。请勿转载和采集!