Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a mutex was locked [duplicate]

Tags:

c

linux

pthreads

In my program, to create a barrier, the main thread sends signals to all the other threads. Now, I want to check if the thread which is executing the signal handler had a mutex locked when the signal handler started. Is there any way to check that inside the signal handler?

like image 541
MetallicPriest Avatar asked Jul 05 '11 15:07

MetallicPriest


1 Answers

Reading through your comments, it appears as though your program is a lot more complex than I thought. If you have 1000's of mutexes, checking to see if they are locked in a signal handler is a bad idea. In fact, if your app is this highly threaded, mixing signals and threads is also an idea I think you should reconsider. The reason for this is mainly inherent in the fact that you can't set a status flag and lock a mutex in an atomic fashion that would be signal-safe. In order to create the proper conditions to support updating a status entry for your mutex, as well as locking the mutex without being interrupted by a signal in the process, you're going to have to create a bunch of code to wrap all your mutex-locking and unlocking functions in critical sections that block any signals the thread could receive, so that you can both lock/unlock a given mutex, as well as set/unset a flag for the mutex's state that can then be read in the signal handler.

A better solution would be to have only a single thread accept signals, with all the other threads blocking the signals you're sending, including the main thread. Then, rather than having to send signals to individual threads, you can simply send signals to the entire process. Upon sending the signal, the only thread that is set for receiving signals and handling them waits with a call to sigwait() for the appropriate signal, and upon receipt, quickly checks an array of values to see which mutexes are set, and which specific thread owns them. For this information your array can be an array of values that are a structure type containing a pointer to the mutex, a locked/unlocked flag, as well as a pointer to the pthread_t of the thread that you can use to get the thread ID value from. For instance, you struct could look something like:

typedef struct mutex_info
{
    pthread_mutex_t* mutex_handle;
    pthread_t* thread_handle;
    int locked;
} mutex_info;

mutex_info mutex_info_array[NUM_MUTEXES];

Then your other threads, without having to worry about asynchronous signal events, can simply update the array values every time they lock or unlock a specific mutex.

like image 179
Jason Avatar answered Sep 21 '22 14:09

Jason