-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreads.c
68 lines (60 loc) · 1.44 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
#include <pthread.h>
#include "main.h"
#include "config.h"
#include "logger.h"
#include "utils.h"
extern state* s;
/**
* Function to handle the position thread
* @param voidS Void * but actually a pointer to state structure
* @return void
*/
void position_thread()
{
//Wait until game start
while(1)
{
pthread_mutex_lock(&(s->mutexGameStarted));
if (s->gameStarted == TRAVELLING)
{
pthread_mutex_unlock(&(s->mutexGameStarted));
break;
}
pthread_mutex_unlock(&(s->mutexGameStarted));
sleep(2);
}
position currentPos;
int i = 0;
while(1)
{
pthread_mutex_lock(&(s->mutexPosition));
currentPos = s->curPos;
pthread_mutex_unlock(&(s->mutexPosition));
send_position(s, currentPos);
//Test regularly if we're still moving
if (++i == 8)
{
pthread_mutex_lock(&(s->mutexGameStarted));
if (s->gameStarted == IMMOBILE)
{
pthread_mutex_unlock(&(s->mutexGameStarted));
break;
}
pthread_mutex_unlock(&(s->mutexGameStarted));
i = 0;
}
sleep(2);
}
return;
}
/**
* Close the threads if they are open when we try to exit
* @param s State structure
* @return 0
*/
int close_threads(state *s)
{
if (s->threadPosition != 0)
pthread_join(s->threadPosition, NULL);
return 0;
}