Add basic SendMsg routine
parent
a5af246855
commit
0b01c5f067
33
mailbox.c
33
mailbox.c
|
@ -1,7 +1,10 @@
|
|||
#include "mailbox.h"
|
||||
#include <semaphore.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
struct mailbox *mailboxes = NULL;
|
||||
static int num_mailboxes = -1;
|
||||
|
||||
/**
|
||||
* Setup the mailboxes global variable
|
||||
|
@ -13,9 +16,12 @@ struct mailbox *mailboxes = NULL;
|
|||
int init_mailboxes(int n) {
|
||||
if (mailboxes != NULL) {
|
||||
return 1;
|
||||
} else if (n <= 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
mailboxes = calloc(n, sizeof(struct mailbox));
|
||||
num_mailboxes = n;
|
||||
for (int i = 0; i < n; i++) {
|
||||
int sem_result = sem_init(&mailboxes[i].send_sem, 0, 1);
|
||||
if (sem_result != 0) {
|
||||
|
@ -45,4 +51,31 @@ void free_mailboxes() {
|
|||
free(mailboxes);
|
||||
// Mark mailboxes as null so freeing is idempotent.
|
||||
mailboxes = NULL;
|
||||
num_mailboxes = -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message to the given mailbox. Blocks if the mailbox is full.
|
||||
*
|
||||
* @param dest The index of the mailbox to send to.
|
||||
* @param message The message to send to the mailbox. Will be copied into the mailbox.
|
||||
*
|
||||
* @reutrn int -1 on error, 0 otherwise.
|
||||
*/
|
||||
int SendMsg(int dest, struct msg *message) {
|
||||
if (dest >= num_mailboxes || dest < 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct mailbox *dest_mailbox = &mailboxes[dest];
|
||||
int wait_result = sem_wait(&dest_mailbox->send_sem);
|
||||
if (wait_result != 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
memcpy(&dest_mailbox->stored_message, message, sizeof(struct msg));
|
||||
// Signal that someone can recieve a message, now that it's stored.
|
||||
sem_post(&dest_mailbox->recv_sem);
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue