Skip to content
Advertisement

POSIX timer hangs up after a few runs

I have created a POSIX timer in the main function of my program. Each thread of the main program is setting the timer so that on expiry of it, the signal handler update one variable which awakes the next thread of the same process.

The timer is working fine most of the time but not always. It sometimes completes the full execution while in other runs, it hangs up. What could be the possible reasons? My suspicion is something related to signal delivery.

Here is the code:

JavaScript

According to this, this program should print

JavaScript

Some of the time it prints like this but most of the time, the program hangs up.

Advertisement

Answer

The signal handler has a race condition. As soon as sem_post is called one of the other threads can start running and its timer can fire before the current signal handler completes. Which will result in the signal handler being called again in another thread. At that point state has not been incremented by the first thread and hence the second signal handler invocation will end up calling sem_post on the wrong semaphore.

One way to fix this is to ensure state is incremented before calling sem_post:

JavaScript

Note that this solution still contains one problem. It does not ensure that the printf calls are in the right sequence.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement