forked from supermartian/lockfree-queue
-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.c
77 lines (65 loc) · 1.62 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
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include "pkt_queue.h"
#define CONSUMER 1
#define PRODUCER 4
#define TEST_NUM 10000000
struct queue_root *queue;
volatile int total = TEST_NUM;
int complete;
void *producer_thread(void *para)
{
int c = TEST_NUM / PRODUCER;
for (; c > 0; c--)
{
int *val = (int *)malloc(sizeof(int));
*val = random();
queue_add(queue, val);
/*
*printf("Adding value %d\n", *val);
*/
}
complete++;
return NULL;
}
void *consumer_thread(void *para)
{
while (total) {
int *val;
val = (int *) queue_get(queue);
if (val != NULL) {
/*
*printf("Getting value %d, %d left\n", *val, queue->size);
*/
__sync_fetch_and_sub(&total, 1);
}
}
return NULL;
}
int main()
{
int p, c;
complete = 0;
pthread_attr_t attr;
pthread_t threads[200];
struct timeval then, now;
gettimeofday(&then, NULL);
srandom((unsigned int)then.tv_usec);
init_queue(&queue);
/* Now create some threads */
pthread_attr_init(&attr);
for (p = 0; p < PRODUCER; p++) {
pthread_create(&threads[p], &attr, producer_thread, NULL);
pthread_join(threads[p], NULL);
}
for (c = 0; c < CONSUMER; c++) {
pthread_create(&threads[p + c], &attr, consumer_thread, NULL);
pthread_join(threads[p + c], NULL);
}
gettimeofday(&now, NULL);
printf("Executions in %.3g seconds\n", now.tv_sec - then.tv_sec + 1e-6 * (now.tv_usec - then.tv_usec));
return 0;
}