I have the following C code where variables prefixed with sm are shared by two processes proc1 and proc2 . Therefore, semaphores are also divided. This code is called repeatedly. Therefore, if I say the previous value, it means the value of the previous iteration.
I noticed in my program that proc1 sometimes skips sem_wait (sem_f2l) without proc2 , executing sem_post (sem_f2l) . I noticed this because sm_value_proc1 and sm_value_proc2 must be the same value in my program as they are, also confirmed by printfs with β> . However, printf with << sometimes shows different values. The difference is that proc1 prints the previous value sm_value_proc2 , because proc1 mysteriously did not wait for sm_f2l to publish 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 ); }
source share