Add ability to setup/destroy mailboxes
parent
369cafe0c1
commit
93130356ec
|
@ -0,0 +1,48 @@
|
|||
#include "mailbox.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
struct mailbox *mailboxes = NULL;
|
||||
|
||||
/**
|
||||
* Setup the mailboxes global variable
|
||||
*
|
||||
* @param n The number of mailboxes to initialize.
|
||||
*
|
||||
* @return int 1 if the mailboxes are already allocated, -1 on error, 0 otherwise.
|
||||
*/
|
||||
int init_mailboxes(int n) {
|
||||
if (mailboxes != NULL) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
mailboxes = calloc(n, sizeof(struct mailbox));
|
||||
for (int i = 0; i < n; i++) {
|
||||
int sem_result = sem_init(&mailboxes[i].send_sem, 0, 1);
|
||||
if (sem_result != 0) {
|
||||
free(mailboxes);
|
||||
return -1;
|
||||
}
|
||||
|
||||
sem_result = sem_init(&mailboxes[i].recv_sem, 0, 0);
|
||||
if (sem_result != 0) {
|
||||
free(mailboxes);
|
||||
sem_destroy(&mailboxes[i].send_sem);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Free the mailboxes global variable.
|
||||
*/
|
||||
void free_mailboxes() {
|
||||
if (mailboxes == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
free(mailboxes);
|
||||
// Mark mailboxes as null so freeing is idempotent.
|
||||
mailboxes = NULL;
|
||||
}
|
|
@ -3,6 +3,8 @@
|
|||
|
||||
#include <semaphore.h>
|
||||
|
||||
extern struct mailbox *mailboxes;
|
||||
|
||||
struct msg {
|
||||
// index of thread that sent the message
|
||||
// if iFrom is -1, then the message is considered invalid.
|
||||
|
@ -24,4 +26,7 @@ struct mailbox {
|
|||
sem_t recv_sem;
|
||||
};
|
||||
|
||||
int init_mailboxes(int n);
|
||||
void free_mailboxes();
|
||||
|
||||
#endif
|
Loading…
Reference in New Issue