-
Notifications
You must be signed in to change notification settings - Fork 0
/
threads.c
137 lines (114 loc) · 2.02 KB
/
threads.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
//======================================================
// threads.c
//
// COMP 3430 - Operating Systems - Assignment 2 Frogger
//
// Helper functions and wrapper for pthreads
//
// @author Andy Lun
// @date June 09, 2017
//======================================================
#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include "console.h"
#include "threads.h"
//=====================================
// FUNCTIONS
//=====================================
void
init_condition()
{
int error = 0;
error = pthread_cond_init(&condition_quit, NULL);
if (error != 0)
{
exit(EXIT_FAILURE);
}
}
void
wait_condition()
{
pthread_cond_wait(&condition_quit, &mutex_condition);
}
void
trigger_condition()
{
if (!end_of_game)
{
end_of_game = true;
pthread_cond_signal(&condition_quit);
finalKeypress();
}
}
void
destroy_condition()
{
pthread_cond_destroy(&condition_quit);
}
void
init_mutex()
{
int error = 0;
error += pthread_mutex_init(&mutex_condition, NULL);
error += pthread_mutex_init(&mutex_console, NULL);
error += pthread_mutex_init(&mutex_frog, NULL);
error += pthread_mutex_init(&mutex_logs, NULL);
if (error != 0)
{
exit(EXIT_FAILURE);
}
}
void
lock_mutex(pthread_mutex_t* mutex)
{
pthread_mutex_lock(mutex);
}
void
unlock_mutex(pthread_mutex_t* mutex)
{
pthread_mutex_unlock(mutex);
}
void
destroy_mutex()
{
pthread_mutex_destroy(&mutex_condition);
pthread_mutex_destroy(&mutex_console);
pthread_mutex_destroy(&mutex_frog);
pthread_mutex_destroy(&mutex_logs);
}
pthread_t
init_thread(char* name, void* func, void* args)
{
pthread_t thread;
if (-1 == pthread_create(&thread, NULL, func, args))
{
exit(EXIT_FAILURE);
}
if (-1 == pthread_setname_np(thread, name))
{
exit(EXIT_FAILURE);
}
return thread;
}
void*
exit_thread()
{
pthread_exit(NULL);
return NULL;
}
void
join_thread(pthread_t thread)
{
pthread_join(thread, NULL);
}
void
sleep_thread(int tick_count)
{
int count;
for (count = 0; count < tick_count && !end_of_game; count++)
{
sleepTicks(1);
}
}