/
main.cpp
99 lines (80 loc) · 1.85 KB
/
main.cpp
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
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "buffer.hpp"
#define NUM_PRODUCERS 4
#define BUFFER_SIZE 8*1024
#define ITERATIONS 1000L * 1000L * 1000L
struct producer_t {
int iterations;
int id;
Buffer<slot_t>* buf;
};
void *
consumer(void *b)
{
Buffer<slot_t> *buf;
const slot_t *slot;
long curr = 0;
buf = (Buffer<slot_t> *)b;
for (;;) {
slot = buf->get(curr);
assert(slot->index == curr);
buf->release(slot);
curr++;
if (curr == ITERATIONS) {
return NULL;
}
}
/* Shouldn't get here. */
assert(NULL);
return NULL;
}
void *
producer(void *p)
{
producer_t* producer;
slot_t* slot;
long iterations;
producer = (producer_t *)p;
for (iterations = producer->iterations; iterations; iterations--) {
slot = producer->buf->claim();
assert(slot);
producer->buf->commit(slot);
}
return NULL;
}
int
main(int argc, char *argv[])
{
Buffer<slot_t> buf(BUFFER_SIZE);
producer_t producers[NUM_PRODUCERS];
pthread_t threads[NUM_PRODUCERS + 1];
int i, ret;
for (i = 0; i < NUM_PRODUCERS; i++) {
producers[i].iterations = ITERATIONS / NUM_PRODUCERS;
producers[i].buf = &buf;
producers[i].id = i;
ret = pthread_create(&threads[i], NULL, producer, &producers[i]);
if (ret != 0) {
fprintf(stderr, "pthread_create(): %s\n", strerror(ret));
exit(EXIT_FAILURE);
}
}
ret = pthread_create(&threads[NUM_PRODUCERS], NULL, consumer, &buf);
if (ret != 0) {
fprintf(stderr, "pthread_create(): %s\n", strerror(ret));
exit(EXIT_FAILURE);
}
for (i = 0; i < NUM_PRODUCERS + 1; i++) {
ret = pthread_join(threads[i], NULL);
if (ret != 0) {
fprintf(stderr, "pthread_join(): %s\n", strerror(ret));
exit(EXIT_FAILURE);
}
}
return EXIT_SUCCESS;
}