#define _GNU_SOURCE #include #include #include #include #include #include "myfutex.h" int lock_val = 0; pthread_t thr; int count; int lock() { int c; if (thr == pthread_self()) { count++; return 0; } while ((c = __sync_val_compare_and_swap(&lock_val, 0, 1)) != 0) { futex_wait(&lock_val, 1); } thr = pthread_self(); return 0; } int unlock() { if (pthread_self() != thr) return EPERM; count--; if (count == 0) { thr = 0; lock_val = 0; futex_wake(&lock_val, 1); } return 0; } void* f_thread0(void *v) { lock(); lock(); printf("Thread 0.\n"); sleep(5); unlock(); unlock(); return NULL; } void* f_thread1(void *v) { lock(); printf("Thread 1.\n"); unlock(); return NULL; } int main() { pthread_t thr0, thr1; pthread_create(&thr0, NULL, f_thread0, NULL); sleep(1); pthread_create(&thr1, NULL, f_thread1, NULL); pthread_exit(0); }