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!
", 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!
",
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!
", sm_value_proc2 );
}
sem_post( sm_f2l );
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…