#include #include #include #include #include /* Implementation of "second attempt" for mutual exclusion (see slides). Uses sleep to make different interleavings more probable. */ /* Tasks: - experiments with time bounds in sleep (how probable is violation) - implement different algoritms: - "first attempt" (alternation) - "third attempt" (deadlock) - peterson's algorithm [ - lamport's bakery algorithm ] - using semaphors (pthread_mutex_lock) - redo the implementation with just one parametrized process specification */ #define K 5 // number of iterations of the loop #define SLEEP 1000000 // max. length of random sleep, 1000000 = 1 s volatile int inCS = 0, flag1 = 0, flag2 = 0; // used for artificial waiting to increase probability of different interleavings void random_sleep() { usleep(rand() % SLEEP); } void *process1(void* arg) { int i; for (i=0; i 1) printf(" Mutual exclusion violated!\n"); random_sleep(); inCS--; // exit section flag1 = 0; } pthread_exit(NULL); } void *process2(void* arg) { int i; for (i=0; i 1) printf(" Mutual exclusion violated!\n"); random_sleep(); inCS--; // exit section flag2 = 0; } pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t p1, p2; srand(time(NULL)); pthread_create(&p1, NULL, process1, NULL); pthread_create(&p2, NULL, process2, NULL); pthread_exit(NULL); }