iHowell
iHowell

Reputation: 2447

Why does unlocking a unique_lock cause my program to crash?

I am running into some odd behavior regarding unique_lock. After creating it, I try to call unlock, but it crashes my program. I have created a minimal example that consistently crashes on the unlock function (used gdb to confirm).

#include <iostream>
#include <string>
#include <mutex>
#include <thread>
#include <chrono>

std::mutex myMutex;

void lockMe()
{
  std::unique_lock lock(myMutex);
  std::cout << "Thread\n";
}

int main()
{
  std::unique_lock lock(myMutex);
  auto c = std::thread(lockMe);
  std::this_thread::sleep_for(std::chrono::seconds(1));
  std::cout << "Main\n";
  myMutex.unlock();
  c.join();
  return 0;
}

Can anyone explain why this is happening?

Upvotes: 3

Views: 3394

Answers (1)

user7860670
user7860670

Reputation: 37486

By creating std::unique_lock lock(myMutex); you are granting mutex lock / unlock control to the lock object. if you manually unlock the mutex while it is still under control of the lock object you will violate that constraint and lock destructor will perform a double unlock attempt.

It is similar to all the RAII wrappers - once you grant resource control to RAII object you should not interfere with it by manually disposing of the resource.

Note that std::unique_lock offers a method to unlock the locked mutex prior to scope end that won't cause problems:

lock.unlock();

Upvotes: 8

Related Questions