How to check in C Posix thread if someone is waiting on a shared semaphore?

1.3k views Asked by At

This is for exception handling scenario in a multi-threaded scenario. More than one threads are working in parallel on some shared resource locked under mutual exclusion whenever needed. If one thread faces an exception, can I use sem_trywait to check if some other thread is waiting on the semaphore and if I find some thread is waiting on a semaphore, will use a flag that exception has occurred and I will issue a sem_post so that waiting thread may unwait and check if some exception occurred before proceeding further. In case exception occurred, the other thread which was otherwise waiting will now proceed towards a graceful exit. Please suggest. My actual qs is: can I use sem_trywait?

1

There are 1 answers

0
wallyk On

The most straightforward solution would be to set up an additional mechanism of thread status. Semaphores are not intended to indicate whether anyone is waiting for them.

In a globally visible variable which is only written by the thread, set it to—say 1—if some thread is waiting for the semaphore and 0 if not. If anyone wants to know if the thread is wanting to obtain the semaphore, check the state of the variable. It shouldn't be too difficult to handle race conditions sampling the variable by ordering operations correctly.