-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
84 lines (69 loc) · 1.84 KB
/
main.cpp
File metadata and controls
84 lines (69 loc) · 1.84 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <slab.h>
#include <test.h>
#define BLOCK_NUMBER (1000)
#define THREAD_NUM (5)
#define ITERATIONS (1000)
#define shared_size (7)
void construct(void *data) {
printf("Shared object constructed.\n");
memset(data, MASK, shared_size);
}
int check(void *data, size_t size) {
int ret = 1;
for (int i = 0; i < size; i++) {
if (((unsigned char *)data)[i] != MASK) {
ret = 0;
}
}
return ret;
}
struct objects_s {
kmem_cache_t *cache;
void *data;
};
int work(struct data_s data) {
char buffer[1024];
int size = 0;
sprintf(buffer, "thread cache %d", data.id);
kmem_cache_t *cache = kmem_cache_create(buffer, data.id, 0, 0);
struct objects_s *objs = (struct objects_s*)kmalloc(sizeof(struct objects_s) * data.iterations);
for (int i = 0; i < data.iterations; i++) {
if (i % 100 == 0) {
objs[size].data = kmem_cache_alloc(data.shared);
objs[size].cache = data.shared;
assert(check(objs[size].data, shared_size));
}
else {
objs[size].data = kmem_cache_alloc(cache);
objs[size].cache = cache;
memset(objs[size].data, MASK, data.id);
}
size++;
}
kmem_cache_info(cache);
kmem_cache_info(data.shared);
for (int i = 0; i < size; i++) {
assert(check(objs[i].data, (cache == objs[i].cache) ? data.id : shared_size));
kmem_cache_free(objs[i].cache, objs[i].data);
}
kfree(objs);
kmem_cache_destroy(cache);
return 0;
}
void run_threads(int(*work)(struct data_s), void *data, int num);
int main() {
void *space = malloc(BLOCK_SIZE * BLOCK_NUMBER);
kmem_init(space, BLOCK_NUMBER);
kmem_cache_t *shared = kmem_cache_create("shared object", shared_size, construct, NULL);
struct data_s data;
data.shared = shared;
data.iterations = ITERATIONS;
run_threads(work, &data, THREAD_NUM);
kmem_cache_destroy(shared);
free(space);
return 0;
}