Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
How to assure that no other thread acquires a lock immediately before you destroy a mutex

In the linux man page for pthread_mutex_destroy, it has the following code snippet below. One thing I don't understand about this procedure to destroy a mutex, is that how do we know that between pthread_mutex_unlock and pthread_mutex_destroy no other thread tries to acquire a lock on said mutex?

Typically, how should this be handled? 1) Should an additional mutex be used to ensure that this cannot happen? 2) Or is it the clients responsibility to not try to increase the reference count after it hits 0?

obj_done(struct obj *op)
{
    pthread_mutex_lock(&op->om);
    if (--op->refcnt == 0) {
        pthread_mutex_unlock(&op->om);
(A)     pthread_mutex_destroy(&op->om);
(B)     free(op);
    } else
(C)     pthread_mutex_unlock(&op->om);
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Something should be done to ensure the mutex isn’t going to get another lock attempt while you’re destroying it, yes. In the example case, with a reference count going to 0 involved, it's reasonable to expect that the thread holding the mutex is also the last thread with a pointer to the object. All the other threads that were using the object are finished with it, have decremented the reference count, and have forgotten about the object. So no thread will be attempting to lock the mutex when pthread_mutex_destroy is executed.

That's the typical design pattern. You don't destroy a mutex until all threads are done with it. The natural lifetime of a mutex means you don’t have to synchronize destroying them.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!