/
main.c
121 lines (93 loc) · 2.53 KB
/
main.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
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#define _XOPEN_SOURCE 500 /* usleep */
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <pthread.h>
#include <wiiuse.h>
#include "controller.h"
#include "controller_state.h"
#include "debug.h"
#include "display.h"
#include "ending.h"
#include "main.h"
#include "rqueue.h"
#include "timer.h"
#include "wiimotes.h"
/* - - - - - - - - - - - - - - - - - - - - */
static struct {
ending_t ending;
rqueue_t buttonsq, hlcommandsq;
controller_state_t cs;
pthread_t threads[3];
} g;
/* - - - - - - - - - - - - - - - - - - - - */
int
main(int argc, char **argv)
{
struct controller_run_args c_args;
struct wiimotes_run_args w_args;
struct display_run_args d_args;
(void)argc;
(void)argv;
sigset_t sigs;
sigfillset(&sigs);
pthread_sigmask(SIG_BLOCK, &sigs, NULL);
if (!timer_init()) {
return EXIT_FAILURE;
}
g.ending = ending_new(false);
g.buttonsq = rqueue_new();
g.hlcommandsq = rqueue_new();
/* controller thread arguments */
c_args.ending = g.ending;
c_args.buttonsq = g.buttonsq;
c_args.hlcommandsq = g.hlcommandsq;
/* wiimote thread arguments */
w_args.ending = g.ending;
w_args.max_num_wiimotes = WIIMOTES_MAX_NUM;
w_args.find_time_in_sec = WIIMOTES_FIND_TIME_IN_SEC;
w_args.buttonsq = g.buttonsq;
w_args.hlcommandsq = g.hlcommandsq;
/* display thread arguments */
d_args.ending = g.ending;
d_args.cs = g.cs;
struct controller_state_s s;
memset(&s, 0, sizeof(s));
g.cs = controller_state_new(&s);
/* start controller thread */
pthread_create(&g.threads[0], NULL, controller_run, &c_args);
/* start wiimotes thread */
pthread_create(&g.threads[1], NULL, wiimotes_run, &w_args);
/* start display thread */
pthread_create(&g.threads[2], NULL, display_run, &d_args);
/* wait for ctrl-c */
sigemptyset(&sigs);
sigaddset(&sigs, SIGINT);
int sig;
while (1) {
sigwait(&sigs, &sig);
if (sig == SIGINT) {
ending_set(g.ending, true);
int num_threads = sizeof(g.threads) / sizeof(pthread_t);
for (int i=0; i<num_threads; i++) {
pthread_join(g.threads[i], NULL);
}
ending_free(g.ending);
rqueue_free(g.buttonsq);
rqueue_free(g.hlcommandsq);
controller_state_free(g.cs);
break;
}
}
print_info("main exiting");
ending_free(g.ending);
rqueue_free(g.buttonsq);
rqueue_free(g.hlcommandsq);
controller_state_free(g.cs);
return EXIT_SUCCESS;
}