#define _GNU_SOURCE #include #include #include #include #include #include "myfutex.h" int lock_val = 0; pthread_t thr; int lock() { int c; if (thr == pthread_self()) return EDEADLK; 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; lock_val = 0; futex_wake(&lock_val, 1); return 0; } void* f_thread0(void *v) { lock(); printf("Thread 0.\n"); sleep(5); unlock(); return NULL; } void* f_thread1(void *v) { lock(); printf("Thread 1.\n"); sleep(5); unlock(); return NULL; } int main() { pthread_t thr0, thr1; pthread_create(&thr0, NULL, f_thread0, NULL); pthread_create(&thr1, NULL, f_thread1, NULL); pthread_exit(0); }