-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathemutex_tests.c
117 lines (96 loc) · 1.98 KB
/
emutex_tests.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/*
* Tests for emutex
*
* Written by Elias Oenal <[email protected]>, released as public domain.
*/
#include "emutex.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>
#ifdef EMUTEX_THREAD_MULTI
#include <pthread.h>
#include <unistd.h>
void emt_test_mt(uint32_t count);
void* emt_mt_thread(void* m);
#endif
void emt_test_st(uint32_t count);
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
#if defined(EMUTEX_THREAD_SINGLE)
emt_test_st(31337);
#endif
#if defined(EMUTEX_THREAD_MULTI)
emt_test_mt(13);
#endif
return 0;
}
#ifdef EMUTEX_THREAD_MULTI
#define NUM_THREADS 20
#define COUNTER 30000
struct shared{
emutex* m; uint64_t* i;
};
void emt_test_mt(uint32_t count)
{
for(uint32_t i = 0; i < count; i++)
{
emutex m;
uint64_t shared_counter = 0;
struct shared s = {&m, &shared_counter};
pthread_t threads[NUM_THREADS];
emutex_init(&m);
emutex_lock(&m);
for(uint32_t t = 0; t < NUM_THREADS; t++)
{
if(pthread_create(&threads[t], NULL, emt_mt_thread, (void*)&s))
{
printf("Failed to spawn thread!\n");
assert(false);
return;
}
}
emutex_unlock(&m);
for(uint32_t t = 0; t < NUM_THREADS; t++)
{
pthread_join(threads[t], NULL);
}
assert(shared_counter == (NUM_THREADS * COUNTER));
}
pthread_exit(NULL);
}
void* emt_mt_thread(void* v)
{
struct shared* s = (struct shared*)v;
for(uint32_t i = 0; i < COUNTER; i++)
{
emutex_lock(s->m);
(*(s->i))++;
emutex_unlock(s->m);
}
pthread_exit((void*)true);
}
#endif /* EMUTEX_THREAD_MULTI */
void emt_test_st(uint32_t count)
{
emutex m;
emutex_init(&m);
for (uint32_t i = 0; i < count; i++)
{
emutex_lock(&m);
emutex_unlock(&m);
emutex_lock(&m);
assert(!emutex_trylock(&m));
assert(!emutex_trylock(&m));
assert(!emutex_trylock(&m));
emutex_unlock(&m);
assert(emutex_trylock(&m));
emutex_unlock(&m);
assert(emutex_trylock(&m));
emutex_unlock(&m);
}
}