简体   繁体   中英

Why has no core dump occurred when I use pthread_mutex_lock twice in the same thread?

#include <pthread.h>
#include <iostream>

int main()
{
    pthread_mutex_t mtx;
    pthread_mutex_init(&mtx, NULL);
    pthread_mutex_lock(&mtx);
    pthread_mutex_lock(&mtx);
    return 0;
}

I run this code in Centos 7, and I except to have a core dump file, but it didn't, the program just dead in the command line.

I thought pthread mutex is non-recursive mutex by default and there is only one thread in my program, so it should be crush when I lock this mutex twice.

You are not guaranteed a core dump when things go wrong. There are a few errors, like dereferencing a null pointer, which linux chooses to catch and provide a core dump file for you (in the right mode), but there's no guarantees. Indeed, many logic errors cannot be detected, thus there is no way to identify that a dump is needed.

In the case of locking a mutex twice, this is "undefined behavior," meaning the library provides no guarantees as to what happens. In the particular case of mutex locking, one could dive into the implementation to learn more of how that specific implementation handles it.

However, in general, its worth noting that there is a reentrant mutex in pthreads, whose sole job is to provide sane behavior if a thread locks the mutex twice. Given that the pthreads developers felt the need to provide both reentrant and non-reentrant mutexes, this suggests that there's some optimizations that can be done on mutex locking that are only safe if a thread doesn't lock it twice.

In this case, it looks like your library has probably used a locking scheme which is unaware as to which thread did the locking. Thus, when you lock it a second time, it doesn't realize that that thread already locks it, and calmly waits for the thread to unlock itself.

A related set of curious behaviors occur if you try to lock a mutex on one thread and unlock it on another (if you need this behavior, use a semaphore instead)

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