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
9#define NUM_THREADS 30
10#define NUM_CYCLES 10000
11
12void* contender(void* p);
13
14lock_set_t g_locks;
15int g_variable = 0;
16long long g_nlocks = 0;
17
18int main()
19{
20 int rv;
21 pthread_t threads[NUM_THREADS];
22
23 rv = lock_set_create(mach_task_self(), &g_locks, 1, SYNC_POLICY_FIFO);
24
25 assert(rv == KERN_SUCCESS);
26
27 for (int i = 0; i < NUM_THREADS; i++)
28 pthread_create(&threads[i], NULL, contender, NULL);
29
30 for (int i = 0; i < NUM_THREADS; i++)
31 pthread_join(threads[i], NULL);
32
33 lock_set_destroy(mach_task_self(), g_locks);
34 printf("Done, %ld locks done\n", g_nlocks);
35 return 0;
36}
37
38void* contender(void* p)
39{
40 for (int i = 0; i < NUM_CYCLES; i++)
41 {
42 int rv;
43 rv = lock_acquire(g_locks, 0);
44 assert(rv == KERN_SUCCESS);
45
46 rv = __sync_add_and_fetch(&g_variable, 1);
47 assert(rv == 1);
48
49 rv = __sync_sub_and_fetch(&g_variable, 1);
50 assert(rv == 0);
51 g_nlocks++;
52
53 rv = lock_release(g_locks, 0);
54 assert(rv == KERN_SUCCESS);
55 }
56
57 return NULL;
58}
59