0

I'm working on linux. In my code I'm trying to run a few threads ( lets say 2 for example) that are trying to lock a RECURSIVE mutex, but only one thread can access and lock the mutex while the second one gets an EBUSY error even after the first thread has unlocked it. I think it's because the mutex is PRIVET and not SHARED.

I'm trying to set the mutex to be both RECRUSIVE and SHARED like this:

    void
MutexCreate(pthread_mutex_t* _m)
{
    pthread_mutexattr_t attr; 

    pthread_mutexattr_init(&attr);
    pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
    pthread_mutex_init(_m, &attr); 
}

(I do check for function errors - and all of them return 0)

Even if I try to make it a DEFAULT SHARED mutex by :

    void
MutexCreate(pthread_mutex_t* _m)
{
    pthread_mutexattr_t attr; 

    pthread_mutexattr_init(&attr);
    pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
    pthread_mutex_init(_m, &attr); 
}

it still remains PRIVET.

Any ideas?

1 Answers1

1

If you really have two threads inside the same process the pshared attribute shouldn't have an influence.

EBUSY is only permitted as a return for pthread_mutex_trylock, so I suppose you used this.

The only explanation that I have is that you maybe locked your mutex several times with the first thread. lock and unlock always come in pairs, make sure that you have as many unlocks as you have locks.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
  • I guess I wasn't informative enough (sometimes I have trouble with explaining myself +I'm new at programming on this level). There are two processes ( a core and test) so I run the core and then begin to run the tests, cores threads number is irrelevant. tests threads number is 2+. And somehow the first test thread does lock & unlock the mutex. After finishing the test it waits for the second thread to finish (I tried `trylock` there (where the first thread waits for the other threads) and its unlocked (but the second thread still sees it as locked). Sorry for not mentioning it before. – user1479830 Jun 28 '12 at 13:17
  • So the mutex is located in a shared memory segment to which core and test have access? What utilities to you use to achieve that? Is it the core process that initializes the mutex? But then you say that the two threads that access this are inside the same process? Perhaps to simplify first start with a mutex that is just shared between these two threads. But your description also shows that a mutex might not the right tool for your goal. You need some sort of usage counter or something like that? – Jens Gustedt Jun 28 '12 at 13:40
  • Sorry for the delay , I don't need a usage counter. I've tried to create this specific mutex as shared but somehow it's still private. – user1479830 Jul 02 '12 at 07:02