#include pthread_spinlock_t spinlock; void* thr_routine(void *arg) { int i; for (i = 0; i < 10; ++i) { pthread_spin_lock(&spinlock); printf("I am %d\n", (int)arg); sleep(1); pthread_spin_unlock(&spinlock); } printf("thread %d exits\n", (int)arg); return (0); } void* thr_routine2(void *arg) { int i; for (i = 0; i < 10; ++i) { while (pthread_spin_trylock(&spinlock)) ; printf("I am %d (trylock)\n", (int) arg); sleep(1); pthread_spin_unlock(&spinlock); } printf("thread %d exits. (trylock)\n", (int)arg); return (0); } int main() { pthread_t td1, td2, td3, td4; if (pthread_spin_init(&spinlock, PTHREAD_PROCESS_PRIVATE)) errx(1, "error init spinlock\n"); pthread_create(&td1, NULL, thr_routine, (void *)1); pthread_create(&td2, NULL, thr_routine, (void *)2); pthread_create(&td3, NULL, thr_routine, (void *)3); pthread_create(&td4, NULL, thr_routine2, (void *)4); pthread_join(td1, NULL); pthread_join(td2, NULL); return (0); }