this repo has no description
1// CFLAGS: -std=c99
2#include <mach/task.h>
3#include <mach/lock_set.h>
4#include <mach/sync_policy.h>
5#include <mach/mach_init.h>
6#include <pthread.h>
7#include <assert.h>
8#include <unistd.h>
9#include <stdio.h>
10
11void* contender1(void* p);
12void* contender2(void* p);
13void setstate(int n);
14
15lock_set_t g_locks;
16int g_state = 0;
17
18int main()
19{
20 int rv;
21 pthread_t threads[2];
22
23 rv = lock_set_create(mach_task_self(), &g_locks, 1, SYNC_POLICY_FIFO);
24
25 assert(rv == KERN_SUCCESS);
26
27 pthread_create(&threads[0], NULL, contender1, NULL);
28 pthread_create(&threads[1], NULL, contender2, NULL);
29
30 pthread_join(threads[0], NULL);
31 pthread_join(threads[1], NULL);
32
33 lock_set_destroy(mach_task_self(), g_locks);
34 return 0;
35}
36
37void setstate(int n)
38{
39 g_state = n;
40 printf("state=%d\n", n);
41}
42
43void* contender1(void* p)
44{
45 setstate(1);
46 sleep(1);
47 lock_acquire(g_locks, 0);
48 setstate(2);
49 lock_handoff(g_locks, 0);
50 setstate(3);
51 sleep(3);
52 setstate(4);
53 lock_handoff_accept(g_locks, 0);
54 lock_release(g_locks, 0);
55
56 return NULL;
57}
58
59void* contender2(void* p)
60{
61 lock_handoff_accept(g_locks, 0);
62 sleep(1);
63 assert(g_state == 3);
64
65 lock_handoff(g_locks, 0);
66 assert(g_state == 4);
67 return NULL;
68}
69