Home > front end >  Mutex waits forever after destroy and re-init
Mutex waits forever after destroy and re-init

Time:12-07

I am trying to create a multi-threaded app in C. At some point the program waits when trying to acquire lock on mutexQueue. but i don't know why. This happens after recreation of the mutex.

for(int i = 80; i<= 8080; i  )
{
    pthread_mutex_init(&mutexQueue,NULL);
    ...
    pthread_mutex_lock(&mutexQueue); <= here it waits forever, after the first iteration (when i=81)
    ...
    pthread_mutex_destroy(&mutexQueue);
}

First time it passes after pthread_mutex_lock therefore it can acquire lock, second time not.

Is there a problem to destroy the mutex and then re-init it after?

Full program execution in real time : https://onlinegdb.com/T5kzCaFUA

EDIT: as @John Carter suggested and reading current pthread documentation (https://pubs.opengroup.org/onlinepubs/007904875/functions/pthread_mutex_destroy.html) it writes :

In cases where default mutex attributes are appropriate, the macro PTHREAD_MUTEX_INITIALIZER can be used to initialize mutexes that are statically allocated. The effect shall be equivalent to dynamic initialization by a call to pthread_mutex_init() with parameter attr specified as NULL, except that no error checks are performed.

i also get the __pthread_mutex_cond_lock_adjust: Assertion (mutex->__data.__kind & 128) == 0' failed. error sometimes, after a long run.

So the error should be somewhere around here, still searching for it.

Thank you.

CodePudding user response:

Are you unlocking the mutex? Destroying a locked mutex results in undefined behaviour:

The pthread_mutex_destroy() function shall destroy the mutex object referenced by mutex; the mutex object becomes, in effect, uninitialized. An implementation may cause pthread_mutex_destroy() to set the object referenced by mutex to an invalid value. A destroyed mutex object can be reinitialized using pthread_mutex_init(); the results of otherwise referencing the object after it has been destroyed are undefined.

phread_mutex_destroy

CodePudding user response:

Is there a problem to destroy the mutex and then re-init it after?

If something might still be using it, yes.

The code you showed is crazy: a shared queue's mutex should live as long as the queue it protects.

Further, the code you show acquires a lock and never unlocks. That doesn't make much sense either.

  •  Tags:  
  • c
  • Related