-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask2.c
More file actions
107 lines (85 loc) · 2.44 KB
/
task2.c
File metadata and controls
107 lines (85 loc) · 2.44 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#ifdef BEST_FIT_LOCAL
#define USE_LOCAL_ALLOCATOR
#include "best_fit_allocator.h"
#endif // BEST_FIT_LOCAL
#ifdef BEST_FIT_GLOBAL
#include "best_fit_allocator.h"
#endif // BEST_FIT_GLOBAL
#ifdef FREE_LIST_LOCAL
#define USE_LOCAL_ALLOCATOR
#include "freelist_allocator.h"
#endif
#ifdef FREE_LIST_GLOBAL
#include "freelist_allocator.h"
#endif
typedef struct Alloc {
int size;
int count;
} Alloc;
pthread_mutex_t mutex;
void *doMalloc(void *arg) {
Alloc *allocData = (Alloc *)arg;
unsigned int seed = time(NULL);
// Perform N allocations and allocate another N/2 blocks of random size.
for (int i = 0; i < allocData->count * 1.5; i++) {
// perform N allocations of random sizes between S and 8*S
int size = (rand_r(&seed) % ((8 * allocData->size) - allocData->size)) +
allocData->size;
// Lock while using queue
pthread_mutex_lock(&mutex);
char *tmp = (char *)myMalloc(size);
if (tmp == NULL) {
printf("Malloc failed, no space available\n");
destroyAllocator();
exit(-1);
}
// randomly(with a 50 % chance)
if (rand_r(&seed) % 2) {
if (tmp != NULL) {
myFree(tmp);
}
}
// Unlock for other threads
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("Usage: ./membench 8 10000 1024\n");
return EXIT_FAILURE;
}
Alloc allocData;
int threadCount = atoi(argv[1]);
allocData.count = atoi(argv[2]);
allocData.size = atoi(argv[3]);
int ret;
pthread_t thread[threadCount];
initAllocator();
// init mutex
pthread_mutex_init(&mutex, NULL);
// create Threads
for (int i = 0; i < threadCount; i++) {
ret = pthread_create(&thread[i], NULL, doMalloc, &allocData);
if (ret != 0) {
fprintf(stderr, "ERROR %d: Cant create thread\n", ret);
return EXIT_FAILURE;
}
}
// Wait for finish
for (int i = 0; i < threadCount; i++) {
ret = pthread_join(thread[i], NULL);
if (ret != 0) {
fprintf(stderr, "ERROR %d: Cant join thread\n", ret);
return EXIT_FAILURE;
}
}
// remove mutex
pthread_mutex_destroy(&mutex);
destroyAllocator();
return EXIT_SUCCESS;
}