-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy paththreads_lock.c
58 lines (46 loc) · 942 Bytes
/
threads_lock.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <uvm/syscalls.h>
#include <stdio.h>
#define NUM_THREADS 100
#define NUM_INCRS 100
u64 thread_ids[NUM_THREADS];
u64 locked = 0;
u64 counter = 0;
void lock()
{
for (;;)
{
// Try to acquire the lock
u64 val = asm (&locked, 0, 1) -> u64 { atomic_cas_u64; };
// If we got the lock, stop
if (val == 0)
break;
}
}
void unlock()
{
asm (&locked, 0) -> void { atomic_store_u64; };
}
void thread_fn()
{
for (int i = 0; i < NUM_INCRS; ++i)
{
lock();
++counter;
unlock();
}
}
int main()
{
for (int i = 0; i < NUM_THREADS; ++i)
{
thread_ids[i] = thread_spawn(thread_fn, NULL);
}
for (int i = 0; i < NUM_THREADS; ++i)
{
thread_join(thread_ids[i]);
}
// Check that the counter value is correct
assert(counter == NUM_THREADS * NUM_INCRS);
printf("counter = %d\n", counter);
return 0;
}