File: mempool.c

package info (click to toggle)
tarantool 1.5.2.20.g5f5d924-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 26,568 kB
  • ctags: 18,697
  • sloc: ansic: 109,092; sh: 21,312; cpp: 20,633; xml: 9,666; asm: 2,488; python: 2,195; java: 1,759; perl: 1,002; makefile: 679
file content (107 lines) | stat: -rw-r--r-- 1,870 bytes parent folder | download | duplicates (2)
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
#include "lib/small/mempool.h"
#include "unit.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

enum {
	OBJSIZE_MIN = 2 * sizeof(int),
	OBJSIZE_MAX = 4096,
	OBJECTS_MAX = 10000,
	OSCILLATION_MAX = 1024,
	ITERATIONS_MAX = 500,
};

struct slab_cache cache;
struct mempool pool;
int objsize;
size_t used;
/* Streak type - allocating or freeing */
bool allocating = true;
/** Keep global to easily inspect the core. */
long seed;

static int *ptrs[OBJECTS_MAX];

static inline void
free_checked(int *ptr)
{
	fail_unless(ptr[0] < OBJECTS_MAX &&
		    ptr[objsize/sizeof(int)-1] == ptr[0]);
	int pos = ptr[0];
	fail_unless(ptrs[pos] == ptr);
	fail_unless(mempool_used(&pool) == used);
	ptrs[pos][0] = ptrs[pos][objsize/sizeof(int)-1] = INT_MAX;
	mempool_free(&pool, ptrs[pos]);
	ptrs[pos] = NULL;
	used -= objsize;
}

static inline void *
alloc_checked()
{
	int pos = rand() % OBJECTS_MAX;
	if (ptrs[pos]) {
		assert(ptrs[pos][0] == pos);
		free_checked(ptrs[pos]);
	}
	if (! allocating)
		return NULL;
	fail_unless(mempool_used(&pool) == used);
	used += objsize;
	ptrs[pos] = mempool_alloc_nothrow(&pool);
	ptrs[pos][0] = pos;
	ptrs[pos][objsize/sizeof(int)-1] = pos;
	return ptrs[pos];
}


static void
basic_alloc_streak()
{
	int oscillation = rand() % OSCILLATION_MAX;
	int i;

	for (i = 0; i < oscillation; ++i) {
		alloc_checked();
	}
}

void
mempool_basic()
{
	int i;
	header();

	mempool_create(&pool, &cache, objsize);

	for (i = 0; i < ITERATIONS_MAX; i++) {
		basic_alloc_streak();
		allocating = ! allocating;
#if 0
		printf("%zu %zu\n", mempool_used(&pool),
		       mempool_total(&pool));
#endif
	}

	mempool_destroy(&pool);

	footer();
}

int main()
{
	seed = time(0);

	srand(seed);

	objsize = rand() % OBJSIZE_MAX;
	if (objsize < OBJSIZE_MIN)
		objsize = OBJSIZE_MIN;

	slab_cache_create(&cache);

	mempool_basic();

	slab_cache_destroy(&cache);
}