I want to return a std::vector
. This std::vector
may be accessed from other threads (read and write). How can I unlock my std::mutex
just after the function has finished returning?
For example in something like:
// Value.cpp
std::vector<int> GetValue()
{
std::lock_guard<std::mutex> lock(mutex);
// Do super smart stuff here
// ...
return m_value;
}
// MyThread.cpp
auto vec = myVec.GetValue();
Now what if "Do super smart stuff here" is empty:
// Value.cpp
std::vector<int> GetValue()
{
std::lock_guard<std::mutex> lock(mutex);
return m_value;
}
// MyThread.cpp
auto vec = myVec.GetValue();
Then is the lock still mandatory? Why?
Use pthread_mutex_lock(3THR) to lock the mutex pointed to by mutex . When pthread_mutex_lock() returns, the mutex is locked and the calling thread is the owner. If the mutex is already locked and owned by another thread, the calling thread blocks until the mutex becomes available.
mutex::lock Locks the mutex. If another thread has already locked the mutex, a call to lock will block execution until the lock is acquired. If lock is called by a thread that already owns the mutex , the behavior is undefined: for example, the program may deadlock.
To solve your issue, you can use std::recursive_mutex , which can be locked/unlocked multiple times from the same thread.
A recursive mutex can be locked repeatedly by the owner. The mutex does not become unlocked until the owner has called pthread_mutex_unlock() for each successful lock request that it has outstanding on the mutex. An errorcheck mutex checks for deadlock conditions that occur when a thread relocks an already held mutex.
Use a std::lock_guard
to handle locking and unlocking the mutex
via RAII, that is literally what it was made for.
int foo()
{
std::lock_guard<std::mutex> lg(some_mutex); // This now locked your mutex
for (auto& element : some_vector)
{
// do vector stuff
}
return 5;
} // lg falls out of scope, some_mutex gets unlocked
After foo
returns, lg
will fall out of scope, and unlock
some_mutex
when it does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With