As you can see in below code, I have used a unique_lock to lock the mutex mtx1. So because of that, lock1 is pointing to mtx1. After that, I have unlocked mtx1. Then I checked again whether lock1 is still pointing to mtx1 or not. I found that it is still pointing to mtx1.
Why is lock1 still pointing to mtx1 even after I unlocked mtx1?
#include <mutex>
#include <thread>
#include <iostream>
#include <thread>
std::mutex mtx1;
void task1()
{
std::cout << "In start of task1 " << std::endl;
std::unique_lock<std::mutex> lock1(mtx1);
if(lock1.mutex() == &mtx1)
{
std::cout << "I have locked the mutex mtx1 " << std::endl;
}
else
{
std::cout << "I have not locked the mutex mtx1 " << std::endl;
}
lock1.unlock(); //used for unlocking
if(lock1.mutex() == &mtx1)
{
std::cout << "I have locked the mutex mtx1 " << std::endl;
}
else
{
std::cout << "I have not locked the mutex mtx1 " << std::endl;
}
}
int main()
{
std::thread t1(task1);
t1.join();
}
output:
In start of task1
I have locked the mutex mtx1
I have locked the mutex mtx1