-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy paththrtestC.c
68 lines (52 loc) · 1.22 KB
/
thrtestC.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
59
60
61
62
63
64
65
66
67
68
/* thread user library functions */
#include "types.h"
#include "user.h"
#undef NULL
#define NULL ((void*)0)
#define PGSIZE (4096)
#define LOOPS 1000000
int ppid;
lock_t xlock;
int global = 0;
int done = 0;
#define assert(x) if (x) {} else { \
printf(1, "%s: %d ", __FILE__, __LINE__); \
printf(1, "assert failed (%s)\n", # x); \
printf(1, "TEST FAILED\n"); \
kill(ppid); \
exit(); \
}
void worker(void *arg_ptr);
int main(int argc, char *argv[])
{
int num_threads = 4;
int i;
ppid = getpid();
lock_init(&xlock);
for(i = 0; i < num_threads; i++) {
int thread_pid = thread_create(worker, 0);
assert(thread_pid > 0);
}
while (done < num_threads) { sleep(1); }
for(i = 0; i < num_threads; i++) {
int join_pid = thread_join(-1);
assert(join_pid > 0);
}
printf(1, "Updating global with locks: %d\n", global);
printf(1, "(Should be %d if no race condition\n", num_threads * LOOPS);
assert(global == (num_threads * LOOPS));
printf(1, "TEST PASSED\n");
exit();
}
void worker(void *arg_ptr) {
int i;
for(i = 0; i < LOOPS; i++) {
lock_acquire(&xlock);
global += 1;
lock_release(&xlock);
}
lock_acquire(&xlock);
done += 1;
lock_release(&xlock);
exit();
}