-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathtest.c
64 lines (49 loc) · 1.47 KB
/
test.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
#include <stdio.h>
#include <unistd.h>
#include "queue.h"
#define BUFFER_SIZE (getpagesize())
#define NUM_THREADS (8)
#define MESSAGES_PER_THREAD (getpagesize() * 2)
void *consumer_loop(void *arg) {
queue_t *q = (queue_t *) arg;
size_t count = 0;
size_t i;
for(i = 0; i < MESSAGES_PER_THREAD; i++){
size_t x;
queue_get(q, (uint8_t *) &x, sizeof(size_t));
count++;
}
return (void *) count;
}
void *publisher_loop(void *arg) {
queue_t *q = (queue_t *) arg;
size_t i;
for(i = 0; i < NUM_THREADS * MESSAGES_PER_THREAD; i++){
queue_put(q, (uint8_t *) &i, sizeof(size_t));
}
return (void *) i;
}
int main(int argc, char *argv[]){
queue_t q;
queue_init(&q, BUFFER_SIZE);
pthread_t publisher;
pthread_t consumers[NUM_THREADS];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&publisher, &attr, &publisher_loop, (void *) &q);
intptr_t i;
for(i = 0; i < NUM_THREADS; i++){
pthread_create(&consumers[i], &attr, &consumer_loop, (void *) &q);
}
intptr_t sent;
pthread_join(publisher, (void **) &sent);
printf("publisher sent %ld messages\n", sent);
intptr_t recd[NUM_THREADS];
for(i = 0; i < NUM_THREADS; i++){
pthread_join(consumers[i], (void **) &recd[i]);
printf("consumer %ld received %ld messages\n", i, recd[i]);
}
pthread_attr_destroy(&attr);
queue_destroy(&q);
return 0;
}