lock_guard
The lock_guard is a class template in C++ that provides a convenient way to acquire and release a mutex automatically. It is part of the C++11 standard library and is defined in the <mutex> header file.
The lock_guard is a simple wrapper around a mutex that locks the mutex in its constructor and unlocks it in its destructor. This ensures that the mutex is always locked when the lock_guard is in scope, and is automatically released when the lock_guard goes out of scope.
Here is an example of using 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 protected by a lock_guard that locks the mtx mutex when the function is called, and unlocks it when the function returns. This ensures that the two threads that call print do not interfere with each other, and that the output is properly synchronized.
Overall, lock_guard is a useful tool for managing mutexes in C++, and can help simplify code that needs to protect shared resources.
原文地址: https://www.cveoy.top/t/topic/brEZ 著作权归作者所有。请勿转载和采集!