You are on page 1of 2

### lock_guard mutex c++ | thread synchronization

#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.

`lock_guard` is a RAII (Resource Acquisition Is Initialization) wrapper around a


mutex. It acquires the mutex in its constructor and releases it in its destructor,
ensuring that the mutex is always released, even if an exception is thrown.

Here's an example of how to use `lock_guard`:

```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"

using namespace std;

mutex mtx;

void Print(char ch) {

this_thread::sleep_for(chrono::milliseconds(2000)); // Long Code Emulator

{
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();
}

this_thread::sleep_for(chrono::milliseconds(2000)); // Long Code Emulator


}

int main() {

SimpleTimer timer;

thread t1(Print, '*');


thread t2(Print, '#');
thread t3(Print, '@');

t1.join();
t2.join();
t3.join();

return 0;
}
```

You might also like