Please help me check if my understanding of std::unique_lock move semantic is correct.
Let's say I have a function myFunc which needs to acquire a mutex at the beginning of its execution.
This function is called from different functions, some of them e.g. myWrapper1 hold the same mutex before myFunc call.
Sometimes I need this lock not be released when myFunc's scope exits.
typedef std::unique_lock<std::mutex> MyLock;
class Example2
{
std::mutex m_data_mutex;
MyLock&& myFunc(MyLock&& lk)
{
bool was_lock = lk.owns_lock();
if( !was_lock ) lk.lock();
std::cout << "myFunc" << std::endl;
if( !was_lock ) lk.unlock();
return std::move(lk);
}
void myWrapper1()
{
MyLock lk(m_data_mutex);
std::cout << "1" << std::endl;
lk = myFunc(std::move(lk));
std::cout << "2" << std::endl;
}
void myWrapper2()
{
MyLock lk(m_data_mutex);
std::cout << "1" << std::endl;
lk.unlock();
lk = myFunc(std::move(lk));
std::cout << "2" << std::endl;
lk.lock();
std::cout << "3" << std::endl;
}
};
So the questions are:
- for
myWrapper1there's a guarantee thatMyLockwill be released only at the end ofmyWrapper1scope, isn't it? - Do I use a correct idiom for this problem?
Aucun commentaire:
Enregistrer un commentaire