1

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.

4

1 に答える 1

2

これはまさに時限ロックの目的です。ライブラリによっては、利用できる場合と利用できない場合があります。

あなたの例:

親:

while(something){
    //do some stuff here.
    sem_post(child_sem);
    while (sem_timed_wait(parent_sem, MAX_WAIT_TIME) == TIMEOUT)
        // check whether you should still continue waiting
}

子:

while(something_else){
    while (sem_timed_wait(child_sem, MAX_WAIT_TIME) == TIMEOUT)
        // check whether you should still continue waiting
    //do some other stuff here.
    sem_post(parent_sem);
}

この方法を使用して、スレッドの堅牢性を高めました。つまり、エラーが発生してスレッドを終了したい場合や、単にスレッドに終了を要求したい場合があるため、スレッドが無期限にブロックされることは望ましくありません。その一方で、できるだけ早く目を覚ます必要があります。

このソリューションは両方の条件を満たします。

于 2012-09-21T14:15:22.887 に答える