Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to std::mutex::lock until function returns

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?

like image 407
Korchkidu Avatar asked Dec 09 '14 16:12

Korchkidu


People also ask

How do you lock a mutex?

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.

How do I use mutex lock in CPP?

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.

Can you lock mutex twice?

To solve your issue, you can use std::recursive_mutex , which can be locked/unlocked multiple times from the same thread.

How do you lock and unlock a mutex?

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.


1 Answers

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.

like image 52
Cory Kramer Avatar answered Oct 15 '22 22:10

Cory Kramer