1 /* $OpenBSD: spinlock.c,v 1.2 2020/04/06 00:01:08 pirofti Exp $ */
2 /* Paul Irofti <paul@irofti.net>, 2012. Public Domain. */
3
4 #include <stdio.h>
5 #include <stdlib.h>
6
7 #include <errno.h>
8 #include <pthread.h>
9 #include <unistd.h>
10
11 #include "test.h"
12
13 void *
foo(void * arg)14 foo(void *arg)
15 {
16 int rc = 0;
17 pthread_spinlock_t l = (pthread_spinlock_t)arg;
18 rc = pthread_spin_trylock(&l);
19 if (rc != 0 && rc != EBUSY) {
20 PANIC("pthread_trylock returned %d", rc);
21 }
22 if (rc == 0) {
23 CHECKr(pthread_spin_unlock(&l));
24 }
25 CHECKr(pthread_spin_lock(&l));
26 CHECKr(pthread_spin_unlock(&l));
27 return NULL;
28 }
29
main()30 int main()
31 {
32 int i;
33 pthread_t thr[10];
34 pthread_spinlock_t l;
35
36 _CHECK(pthread_spin_init(&l, PTHREAD_PROCESS_SHARED), == ENOTSUP,
37 strerror(_x));
38
39 CHECKr(pthread_spin_init(&l, PTHREAD_PROCESS_PRIVATE));
40 for (i = 0; i < 10; i++) {
41 printf("Thread %d started\n", i);
42 CHECKr(pthread_create(&thr[i], NULL, foo, (void *)l));
43 }
44 for (i = 0; i < 10; i++) {
45 CHECKr(pthread_join(thr[i], NULL));
46 }
47 CHECKr(pthread_spin_destroy(&l));
48
49 SUCCEED;
50 }
51