Is it possible to build a sort of combined semaphore/spin lock in C?
That is, I want a thread control structure which supports:
- Periodically waking up the thread to check the state of some variable. (like a spin lock)
- Automatically waking the thread early if the state of the structure is altered by another thread (like sem_wait/sem_post).
For example in a program like this:
Parent:
while(something){
//do some stuff here.
sem_post(child_sem);
sem_wait(parent_sem);
}
Child:
while(something_else){
sem_wait(child_sem);
//do some other stuff here.
sem_post(parent_sem);
}
I would like the parent to unblock if the child fails to set parent_sem within 5 seconds, but also to unblock before 5 seconds have passed if the child has set parent_sem early, while minimizing the number of CPU cycles expended checking and re-checking the state of parent_sem over those 5 seconds. I know I can do this with a spin lock, but setting the waiting period to be high (i.e. 1 second) means wasting almost 1 second most of the time. Setting it to be low (e.g. 100ms) means doing 50 checks in the event the child times out. Neither of these is a nice solution.