I have the following C code, where variables prefixed by sm are shared by two processes proc1 and proc2. Therefore the semaphores are also shared. This code is called repeatedly. So if I say previous value, that means value of a previous iteration.
I notice in my program that proc1 sometimes passes sem_wait( sem_f2l ) without proc2 executing sem_post( sem_f2l ). This I notice because sm_value_proc1 and sm_value_proc2 are supposed to be of same value in my program, which they are, as also confirmed by the printfs with >>>. However, the printf with <<< sometimes show different values. The difference is due to proc1 printing the previous value of sm_value_proc2 since proc1 mysteriously doesn't sometimes wait for sm_f2l to be posted by proc2.
Any idea what is going wrong here?
// semaphores are initialized like this -> sem_init( sm_l2f, 1, 0 );
// Note that sm_l2f and sm_f2l are pointers to sem_t
// sm_condition is assigned here by proc1
if ( is_proc1 )
{
sem_post( sm_l2f );
// proc2_value should be updated by now here, but sometimes sem_wait
// passes without waiting for proc2 to post sm_f2l!
sem_wait( sm_f2l );
if ( sm_condition )
{
sm_value_proc1 = calc_value();
printf( ">>> proc1 value = %u!\n", sm_value_proc1 );
// If sem_wait and sem_post are working properly, printf will print
// the same value for sm_value_proc1 and sm_value_proc2 here, which it
// sometimes doesn't, as the previous value of
// sm_value_proc2 is printed.
printf( "<<< proc1 value = %u, proc2 value = %u, barrier_no = %d!\n",
sm_value_proc1, sm_value_proc2, barrier_no[tid] );
}
}
else // is proc2
{
sem_wait( sm_l2f );
if ( sm_condition )
{
sm_value_proc2 = calc_value();
printf( ">>> proc2 value = %u!\n", sm_value_proc2 );
}
sem_post( sm_f2l );
}
Maybe this is a copy/paste error in the question (you are using copy/paste from the real code, right?), but it looks like you have a bug in proc2's handling:
Then again, maybe it's a copy/paste error in the actual code?
Also - don't forget that
sem_wait()
can unblock due to a signal.