// Class 24, section 3: two threads, two locks, taken in opposite orders.
// Most runs never finish: each thread holds the lock the other is waiting
// for. gdb shows it: run it under gdb, Ctrl-C, info threads, thread apply all bt.
#include <stdio.h>
#include <pthread.h>

#define ROUNDS 100000

pthread_mutex_t a = PTHREAD_MUTEX_INITIALIZER;   // guards one thing
pthread_mutex_t b = PTHREAD_MUTEX_INITIALIZER;   // guards another
long moved = 0;                                  // what both threads change

// takes a, then b, and moves something, ROUNDS times
void * first(void * arg) {
    for (int i = 0; i < ROUNDS; i++) {
        pthread_mutex_lock(&a);
        pthread_mutex_lock(&b);
        moved++;
        pthread_mutex_unlock(&b);
        pthread_mutex_unlock(&a);
    }
    return NULL;
}

// takes b, then a, and moves something, ROUNDS times
void * second(void * arg) {
    for (int i = 0; i < ROUNDS; i++) {
        pthread_mutex_lock(&b);
        pthread_mutex_lock(&a);
        moved--;
        pthread_mutex_unlock(&a);
        pthread_mutex_unlock(&b);
    }
    return NULL;
}

int main() {
    pthread_t t1;
    pthread_t t2;
    pthread_create(&t1, NULL, first, NULL);
    pthread_create(&t2, NULL, second, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    printf("moved %ld\n", moved);
}
