-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.c
92 lines (76 loc) · 2.09 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
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include "message-queue.h"
messagequeue_t* threadQueue;
void* threadFunc (void* arg) {
int i;
message_t msg;
// 1 extra loop to give a bit of time for main to catch up
for (i = 0; i < 6; ++i) {
sleep(1);
if (MessageQueue.pop(threadQueue, &msg) == ERROR_VAL) {
if (errno != ENOMSG) {
perror("Popping from threadQueue failed");
return (void*)EXIT_FAILURE;
}
else {
continue;
}
}
printf("recieved: %s\n", (const char*)msg.data);
free(msg.data); // we malloc'd earlier, remember? always free your mallocs!
}
return (void*)EXIT_SUCCESS;
}
int main (int argc, char* argv[]) {
threadQueue = malloc(sizeof(messagequeue_t));
if (threadQueue == NULL) {
errno = ENOMEM;
perror("Allocating threadQueue failed");
return EXIT_FAILURE;
}
if (MessageQueue.new(threadQueue) == ERROR_VAL) {
perror("Intializing threadQueue failed");
return EXIT_FAILURE;
}
pthread_t thread;
if (pthread_create(&thread, NULL, threadFunc, NULL) != 0) {
perror("Creating thread failed");
return EXIT_FAILURE;
}
int i;
const char* text = "hello!";
message_t msg;
msg.type = 1;
for (i = 0; i < 5; ++i) {
sleep(1);
msg.data = malloc(strlen(text)+1); // we malloc this! don't forget to free!
if (msg.data == NULL) {
errno = ENOMEM;
perror("Allocating message data failed");
return EXIT_FAILURE;
}
// Copy the data to prevent race conditions
strcpy(msg.data, text);
if (MessageQueue.push(threadQueue, &msg) == ERROR_VAL) {
perror("Pushing to threadQueue failed");
return EXIT_FAILURE;
}
}
void* retValue;
if ((errno = pthread_join(thread, &retValue)) != 0) {
perror("Joining thread failed");
return EXIT_FAILURE;
}
if (MessageQueue.delete(threadQueue) == ERROR_VAL) {
perror("Deleting threadQueue failed");
return EXIT_FAILURE;
}
free(threadQueue);
threadQueue = NULL;
if (retValue == (void*)EXIT_FAILURE)
return EXIT_FAILURE;
return EXIT_SUCCESS;
}