add make file, header, and extra code to deque
[model-checker-benchmarks.git] / ms-queue / main.c
1 #include <stdlib.h>
2 #include <assert.h>
3 #include <stdio.h>
4 #include <threads.h>
5
6 #include "my_queue.h"
7
8 static int procs = 2;
9 static int iterations = 1;
10 static queue_t *queue;
11 static thrd_t *threads;
12 static int num_threads;
13
14 int get_thread_num()
15 {
16         thrd_t curr = thrd_current();
17         int i;
18         for (i = 0; i < num_threads; i++)
19                 if (curr.priv == threads[i].priv)
20                         return i;
21         assert(0);
22         return -1;
23 }
24
25 static void parse_args(int argc, char **argv)
26 {
27         extern char *optarg;
28         int c;
29
30         while ((c = getopt(argc, argv, "i:p:")) != EOF) {
31                 switch (c) {
32                 case 'i':
33                         iterations = atoi(optarg);
34                         break;
35                 case 'p':
36                         procs = atoi(optarg);
37                         break;
38                 default:
39                         assert(0);
40                 }
41         }
42 }
43
44 static void main_task(void *param)
45 {
46         unsigned int i, j;
47         unsigned int val;
48         int pid = *((int *)param);
49
50         for (i = 0; i < iterations; i++) {
51                 val = 1 + pid * iterations + i;
52                 printf("worker %d, enqueueing: %u\n", pid, val);
53                 enqueue(queue, val);
54
55                 val = dequeue(queue);
56                 printf("worker %d, dequeued: %u\n", pid, val);
57         }
58 }
59
60 int user_main(int argc, char **argv)
61 {
62         int i;
63         int *param;
64
65         parse_args(argc, argv);
66
67         queue = calloc(1, sizeof(*queue));
68         assert(queue);
69
70         num_threads = procs;
71         threads = malloc(num_threads * sizeof(thrd_t));
72         param = malloc(num_threads * sizeof(*param));
73
74         init_queue(queue, num_threads);
75         for (i = 0; i < num_threads; i++) {
76                 param[i] = i;
77                 thrd_create(&threads[i], main_task, &param[i]);
78         }
79         for (i = 0; i < num_threads; i++)
80                 thrd_join(threads[i]);
81
82         free(param);
83         free(threads);
84         free(queue);
85
86         return 0;
87 }