[SOLVED] Kill thread during it's waiting for pthread_mutex_lock

Issue

I’m coding in C on Ubuntu.
I have more than 2 threads like this:

void * thread(void)
{

    retry:
      pthread_mutex_lock(&mutex);
        //DO SOMETHING
      pthread_mutex_unlock(&mutex);
    goto retry;

}

So I have thread1,thread2,…,threadN.
Sometimes thread2,…,threadN can be killed from thread1 with pthread_cancel().

This pthread_cancel() is inserted inside the mutex so It’s called in a safe zone.

Every time thread1 call pthread_cancel() on a threadK, threadK is waiting for a mutex, so it has called function pthread_mutex_lock().

This thing can create a problem in my program?
I have a bug in my program, I think that I have a deadlock, but I don’t understand why. I’m thinking that this is the reason.

Thanks to all in advance.

Solution

Do not use thread cancellation if you can possibly avoid it. There are quite a few issues and gotchas to contend with.

One class of issues has to do with resource cleanup. Although POSIX defines a mechanism for registering cleanup handlers to address this issue, it takes a great deal of painstaking work to ensure that all resources — allocated memory, open files, mutexes and semaphores, general shared state — are properly cleaned up by those means. It is very easy for a thread to, say, fail to unlock a mutex it holds locked when it is canceled, thus deadlocking each and every thread that subsequently attempts unconditionally to lock it.

Another, more subtle class of issues has to do with at what points a thread actually can be cancelled. By default, a thread with a pending cancellation signal will terminate when it next reaches a cancellation point or if it is already blocked at a cancellation point. A fair number of POSIX functions either definitely are or may be cancellation points, but not all.

In particular, pthread_mutex_lock() is not a cancellation point. Thus, if you cancel a thread that is blocked in pthread_mutex_lock, it will not immediately be canceled. In principle, it might successfully lock the mutex and then proceed until it reaches a cancellation point, or it might return without locking the mutex (with a non-zero return code to indicate the nature of the error). Either could cause trouble for you, but the former seems especially poised to set you up for a deadlock. In practice, pthread_mutex_lock() is documented to not return EINTR, leading me to expect that the former alternative will be exhibited: cancellation requests will not cause a thread blocked in pthread_mutex_lock() to terminate without acquiring the mutex and returning.

Answered By – John Bollinger

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.