Hello I am new to this and I would like to know what I am understanding wrong. I have a program:
#include <pthread.h>
pthread_mutex_t lock;
pthread_mutexattr_t att;
int main () {
pthread_mutexattr_init (&att);
pthread_mutexattr_settype (&att, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init (&lock, &att);
pthread_mutex_lock (&lock);
pthread_mutex_lock (&lock);
pthread_mutex_unlock (&lock);
}
PTHREAD_MUTEX_RECURSIVE means that the lock remembers how many times has been locked. But this program still finishes without any errors. Even when I don't call unlock at all ... I would expect some error that I have still locked lock or something like that or something...Does it somehow unlock automatically? (I compile my code as gcc main.c -pthread
)
CodePudding user response:
I would expect some error that I have still locked lock
Nope. Nothing prevents the process from terminating or will complain about the process terminating while the lock still is locked. That would be like expecting an error because you malloc()
d an object, but didn't free it before the process terminated. Like expecting an error because you opened a file but didn't close it.
The lock—like the virtual memory occupied by the malloc()d object, like the open file handle—is a resource that belongs exclusively to the process, and when you kill the process, all such resources are automatically destroyed/released/freed/etc.
P.S., This could be a good reason to move toward C and, in particular, the RAII design pattern that is enabled by C . RAII is a way to guarantee that open files, allocated objects, locked locks, etc. won't be forgotten.
CodePudding user response:
Even when I don't call unlock at all ... I would expect some error that I have still locked lock or something like that or something
Why?
It is not inherently erroneous for a program to terminate while it holds a mutex locked. Moreover, C does not guarantee any runtime diagnostics even when the program does something genuinely wrong. Sometimes you do get diagnostics under such circumstances, but often you do not.
...Does it somehow unlock automatically?
No, but that does not matter in the example presented because the mutex itself is destroyed when the program terminates.
If it were a process-shared mutex to which another process also had access then it would be a semantic error for a process to terminate while holding it locked. But probably still not one that you could expect a diagnostic about.