Professional Documents
Culture Documents
#multithreading
[[(thread)]] [[1.th.parameters]] [[2.th.&return]] [[3.th.lambda]] [[4.th.methods]]
[[5.mutex]] [[6.mutex.lock_guard]] [[7.Deadlock]] [[8.recursive_mutex]] [[9.
unique_lock]]
---
In multithreaded programming, it is crucial to ensure that threads accessing shared
resources do not interfere with each other and cause undefined behavior. One way to
achieve this is by using synchronization primitives like mutexes, which prevent
multiple threads from accessing the same resource at the same time.
However, manually acquiring and releasing a mutex can be tedious and error-prone.
To simplify this process, C++ provides the `lock_guard` class.
```cpp
#include <iostream>
#include <mutex>
#include <thread>
std::mutex my_mutex;
void thread_func() {
std::lock_guard<std::mutex> lock(my_mutex);
std::cout << "Thread ID: " << std::this_thread::get_id() << " acquired the
lock." << std::endl;
// do some work...
}
int main() {
std::thread t1(thread_func);
std::thread t2(thread_func);
t1.join();
t2.join();
return 0;
}
```
In this example, we create a mutex `my_mutex` and two threads that call the
`thread_func` function. Inside `thread_func`, we create a `lock_guard` object
`lock` that acquires `my_mutex` and prints a message indicating that the thread has
acquired the lock. The lock is automatically released when `lock` goes out of scope
at the end of the function.
Note that `lock_guard` is not copyable or movable, which means that it cannot be
copied or moved to another object. This is intentional, as it ensures that the
mutex is always released when the `lock_guard` object goes out of scope.
Using `lock_guard` can simplify the process of acquiring and releasing mutexes,
making multithreaded programming less error-prone and more efficient.
## My Example
```cpp
#include <iostream>
#include <mutex>
#include <thread>
#include "SimpleTimer.h"
mutex mtx;
{
lock_guard<mutex> guard(mtx);
//mtx.lock();
for (int i = 0; i < 5; ++i) {
for (int i = 0; i < 10; i++) {
cout << ch;
this_thread::sleep_for(chrono::milliseconds(20));
}
cout << endl;
}
cout << endl;
//mtx.unlock();
}
int main() {
SimpleTimer timer;
t1.join();
t2.join();
t3.join();
return 0;
}
```