-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage.c
More file actions
92 lines (82 loc) · 1.97 KB
/
Copy pathmessage.c
File metadata and controls
92 lines (82 loc) · 1.97 KB
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
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "message.h"
#include "states.h"
struct message *mailqueue = NULL;
// Todo make this smarter so it does not add duplicates....
int send_message(int sender, int receiver, int message, double timestamp,
void *extrainfo) {
struct message *ptr = mailqueue;
struct message *tmp;
tmp = malloc(sizeof(struct message));
tmp->sender = sender;
tmp->receiver = receiver;
tmp->msg = message;
tmp->dispatchtime = timestamp;
tmp->extrainfo = extrainfo;
tmp->next = NULL;
if (ptr == NULL) {
mailqueue = tmp;
return 1;
}
if (timestamp < ptr->dispatchtime) {
tmp->next = mailqueue;
mailqueue = tmp;
return 1;
}
while (ptr->next != NULL) {
if (timestamp < ptr->next->dispatchtime) {
tmp->next = ptr->next;
ptr->next = tmp;
return 1;
}
ptr = ptr->next;
}
ptr->next = tmp;
return 1;
}
/* If we were doing obj oriented programming this
would be in the object, were not so its all here */
void handle_message(struct message *ptr) {
switch (ptr->msg) {
case HONEYIMHOME:
people[ptr->receiver].laststate =
people[ptr->receiver].state;
people[ptr->receiver].state = CookStew;
break;
case ROASTDONE:
people[ptr->receiver].laststate =
people[ptr->receiver].state;
people[ptr->receiver].state = GetCookedStew;
break;
case HITS:
people[ptr->receiver].laststate =
people[ptr->receiver].state;
people[ptr->receiver].state = Fight;
// Should do some extra stuff here....
break;
default:
printf("Undefined message from p%d to p%d\n",
ptr->sender, ptr->receiver);
}
}
void process_mail() {
struct message *ptr, *last;
double curtime = time(NULL);
ptr = mailqueue;
last = NULL;
while (ptr != NULL) {
if (ptr->dispatchtime < curtime) {
handle_message(ptr);
if (last == NULL) mailqueue = ptr->next;
else last->next = ptr->next;
free(ptr);
last = ptr->next;
if (last != NULL) ptr = last->next;
else ptr = NULL;
} else {
break;
}
}
}