Add basic (untested) adder thread implementation

master
Nick Krichevsky 2019-09-23 12:40:05 -04:00
parent 3ff3a405c6
commit 2c83d753d9
2 changed files with 68 additions and 0 deletions

61
adder.c Normal file
View File

@ -0,0 +1,61 @@
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include "adder.h"
#include "mailbox.h"
/**
* Read all of the values from the given mailbox id and then send it back to mailbox 0.
*
* @param raw_mailbox_id A ponter to an integer holding the mailbox id this thread should read from.
* @return void* Returns a pointer to a return code. -1 on error, 0 otherwise. Must be freed by caller.
*/
void *adder(void *raw_mailbox_id) {
int mailbox_id = *(int*)(raw_mailbox_id);
int *ret_val = malloc(sizeof(int));
// If we're thread 0, we shouldn't be running adder.
// Any thread id below 0 is invalid.
if (mailbox_id <= 0) {
*ret_val = -1;
return ret_val;
}
int num_messages = 0;
int total_value = 0;
int start_time = time(NULL);
struct msg message;
while (true) {
int recv_result = RecvMsg(mailbox_id, &message);
if (recv_result != 0) {
*ret_val = -1;
return ret_val;
}
// If we have a negative value, we're done receiving messages.
if (message.value < 0) {
break;
}
num_messages++;
total_value += message.value;
sleep(1);
}
int end_time = time(NULL);
struct msg res_mesage = {
.iFrom = mailbox_id,
.value = total_value,
.cnt = num_messages,
.tot = end_time - start_time,
};
int send_result = SendMsg(0, &res_mesage);
if (send_result <= 0) {
*ret_val = -1;
return ret_val;
}
*ret_val = 0;
return ret_val;
}

7
adder.h Normal file
View File

@ -0,0 +1,7 @@
#ifndef ADDER_H
#define ADDER_H
// silly name, but it's required...
void *adder(void *raw_mailbox_id);
#endif