Professional Documents
Culture Documents
Unique - Lock
Unique - Lock
#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 C++, a `unique_lock` is a class template that provides a RAII-style mechanism
for locking and unlocking a mutex. It provides additional flexibility over the
`lock_guard` class template because it allows the mutex to be unlocked before the
`unique_lock` object is destroyed.
The `unique_lock` is an STL container for a mutex, which allows a thread to lock
and unlock the mutex multiple times, and also allows the thread to unlock the mutex
before it goes out of scope.
Here, `my_mutex` is the mutex that we want to lock, and `my_lock` is the
`unique_lock` object that will be responsible for locking and unlocking the mutex.
The `unique_lock` object has two main methods: `lock()` and `unlock()`. When the
`lock()` method is called, the mutex is locked. When the `unlock()` method is
called, the mutex is unlocked.
The `unique_lock` class also provides a mechanism for deferring locking of the
mutex. This can be useful in cases where we want to perform some operations before
locking the mutex. The `unique_lock` class provides the `defer_lock` constructor
that creates the `unique_lock` object without locking the mutex. The `lock()`
method can be called later to lock the mutex.
std::mutex my_mutex;
void my_function()
{
std::unique_lock<std::mutex> my_lock(my_mutex);
std::cout << "Thread " << std::this_thread::get_id() << " is executing." <<
std::endl;
}
int main()
{
std::thread t1(my_function);
std::thread t2(my_function);
t1.join();
t2.join();
return 0;
}
```
In this example, we have a mutex `my_mutex` and a function `my_function` that locks
the mutex using a `unique_lock`. We create two threads that call the `my_function`
function. Since the mutex is locked by the `unique_lock`, only one thread can
execute the function at a time. The output of this program would be something like:
```cpp
Thread 140232466480128 is executing.
Thread 140232458087424 is executing.
```
In summary, `unique_lock` is a very useful class template that provides a safe and
flexible way to lock and unlock mutexes in C++. It allows us to lock and unlock
mutexes multiple times, and also allows us to defer locking until we are ready to
execute our critical section.
## My Example
```cpp
#include <iostream>
#include <mutex>
#include <thread>
#include "SimpleTimer.h"
mutex mtx;
ul.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;
ul.unlock();
int main() {
SimpleTimer timer;
t1.join();
t2.join();
t3.join();
return 0;
}
```