Question

I have this minimal code:

#include <mutex>
#include <iostream>

std::mutex themutex;

void f1()
{ 
  std::cout << "1" << std::endl;
  std::lock_guard<std::mutex> local_mutex(themutex);
  std::cout << "2" << std::endl;
}

void f2()
{
  std::cout << "3" << std::endl;
  std::lock_guard<std::mutex> local_mutex(themutex);
  std::cout << "4" << std::endl;
  f1();
  std::cout << "5" << std::endl;
}

int main(void)
{
  f2();
  return 0;
}

I compile and run with

g++ -std=c++11 test_mutex.cc -o test_mutex && ./test_mutex

and I get this output:

3
4
1
2
5

Why?

I expect the program to lock after printing "1" and never to return.

Was it helpful?

Solution

From 30.4.1 ("Mutex requirements"):

The expression m.lock() shall be well-formed and have the following semantics:

Requires: If m is of type std::mutex or std::timed_mutex, the calling thread does not own the mutex.

You're violating the requirements, and so you cannot expect any behaviour guaranteed by the standard.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top