#include #include #include #include #include static int x = 0; static int y = 0; static int flagA = 0; static int flagB = 0; static int turn = 0; //Consumer void *procA() { for ( ;; ) { //hungry, ask cheff to prepare something flagA = 1; turn = 1; while ( flagB && turn == 1 ) { usleep(1); } //eat printf("Turn A\n"); y = 0; flagA = 0; } pthread_exit(NULL); } //Producer void *procB() { for ( ;; ) { //prepare food, and allow eating flagB = 1; turn = 0; while ( flagA && turn == 0 ) { usleep(1); } printf("Turn B\n"); y = 1; flagB = 0; } pthread_exit(NULL); } int main (int argc, char * argv[]) { //create 2 threads pthread_t thread0, thread1; pthread_create(&thread0, NULL, procA, NULL); pthread_create(&thread1, NULL, procB, NULL); //debugging for ( ;; ) { printf("flagA:%i flagB:%i turn:%i, y:%i\n", flagA, flagB, turn, y); sleep(1); } pthread_exit(NULL); return(EX_OK); }