#include #include #include volatile bool flag[2]; volatile int turn; int other( int x ) { return x == 0 ? 1 : 0; } volatile int critical; void *worker( void *_tid ) { int tid = (int)_tid; flag[ tid ] = true; turn = other( tid ); while ( flag[ other( tid ) ] && turn == other( tid ) ) { } // critical start ++critical; --critical; // end flag[ tid ] = false; return 0; } int main() { pthread_t t1, t2; pthread_create( &t1, 0, worker, (void *)0 ); pthread_create( &t2, 0, worker, (void *)1 ); while ( true ) assert( critical <= 1 ); /* ERROR */ pthread_join( t1, 0 ); pthread_join( t2, 0 ); return 0; }