4
votes

I want to move my code from boost- to std-threads. While I thought it should be quite straight forward I'm running into weird problems. The code below is a minimal example which fires an assertion "f:\dd\vctools\crt_bld\self_x86\crt\src\thr\mutex.c(131):unlock of unowned mutex" with VS2012. Searching for this brings up older bug reports which (i think) should be already fixed.

int result = 0;
std::mutex m;
m.lock();
std::thread t1([&](){
    result = 42;
    m.unlock();
});
m.lock();
std::cout << result << std::endl;
t1.join();

Can someone explain to me why this doesn't work?

Thanks

1
You're locking m twice? - Seth Carnegie

1 Answers

11
votes

m.unlock() requires that the calling thread owns the mutex. Your code does not meet that requirement (as the unlock()ing thread never calls m.lock()) and so the program's behavior is undefined.