简体   繁体   中英

Why locking a std::mutex doesn't block the thread

I wrote the following code to test my understanding of std::mutex

int main() {
    mutex m;
    m.lock();
    m.lock(); // expect to block the thread
}

And then I got a system_error: device or resource busy . Isn't the second m.lock() supposed to block the thread?

From std::mutex :

A calling thread must not own the mutex prior to calling lock or try_lock.

and from std::mutex::lock :

If lock is called by a thread that already owns the mutex, the program may deadlock. Alternatively, if an implementation can detect the deadlock, a resource_deadlock_would_occur error condition may be observed.

and the exceptions clause:

Throws std::system_error when errors occur, including errors from the underlying operating system that would prevent lock from meeting its specifications. The mutex is not locked in the case of any exception being thrown.

Therefore it is not supposed to block the thread. On your platform, the implementation appears to be able to detect when a thread is already the owner of a lock and raise an exception. This may not happen on other platforms, as indicated in the descriptions.

Isn't the second m.lock() supposed to block the thread?

No, it gives undefined behaviour. The second m.lock() breaks this requirement:

C++11 30.4.1.2/7 Requires: If m is of type std::mutex or std::timed_mutex , the calling thread does not own the mutex.

It looks like your implementation is able to detect that the calling thread owns the mutex and gives an error; others may block indefinitely, or fail in other ways.

( std::mutex wasn't mentioned in the question when I wrote this answer.)

It depends on the mutex library and mutex type you're using - you haven't told us. Some systems provide a "recursive mutex" that is allowed to be called multiple times like this only if it happens from the same thread (then you must have a matching number of unlocks before another thread can lock it), other libraries consider this an error and may fail gracefully (as yours has) or have undefined behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM