PThread robust mutex not working

526 views Asked by At

For interprocess programs, when a process acquires a mutex lock and the process is killed by a user, the lock never gets unlocked and another process which is waiting to acquire the same lock, just keeps waiting.

I did an extensive search and found that pthreads has the concept of a robust lock to solve the problem, but on trying it, the ordinary locking between processes itself is not working. For the below code, I opened two terminals and ran the executable in both terminals. In both, the program acquired the lock immediately. Expected behaviour was that the first executable I ran would acquire the lock and the second executable would wait for 30 seconds. But that doesn't happen. Have I implemented it wrong? (Compile with -lpthread)

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

pthread_mutex_t shm_mutex;

int main(void)
{
    int err;
    pthread_mutexattr_t mattr;
    std::cout<<"Beginning\n";


    err = pthread_mutexattr_init(&mattr); if (err) return err;
    err = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED); if (err) return err;
    err = pthread_mutex_init(&shm_mutex, &mattr); if (err) return err;
    err = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);


    std::cout<<"Before locking\n";
    //err = pthread_mutexattr_destroy(&attr); if (err) return err;
    err = pthread_mutex_lock(&shm_mutex); if (err) return err;
    std::cout<<"locked\n";

    sleep(30);

    err = pthread_mutex_unlock(&shm_mutex); if (err) return err;
    std::cout<<"Unlocked\n";
    err = pthread_mutex_destroy(&shm_mutex); if (err) return err;

    return 0;
}   
1

There are 1 answers

2
David Schwartz On

You have two related problems:

  1. The second process called pthread_mutex_init on the mutex, which destroys it, since it was already created and locked by the first process.

  2. You didn't actually share the mutex by putting it in shared memory. You had each process create its own mutex in its own address space.