A mailbox is a place for threads to deposit and retrieve messages. Thus, a mailbox can be used by many threads. For our purpose, a message is simply an integer and a mailbox can hold no more than one message (i.e., the capacity of a mailbox is 1). Threads that put messages into a mailbox are senders and threads retrieves messages from a mailbox are receivers.
In fact, if we consider senders as producers and receivers as consumers, a mailbox is simply a bounded buffer with only one element. Thus, its implementation is very simple. We shall return to this later.
#include "mbox.h" mbox_t Box; int msg_init(mbox_t *Box); int msg_send(mbox_t *Box, int *Data); int msg_receive(mbox_t *Box, int *Data);
As mentioned earlier, a mailbox is simply a bounded buffer of one entry. The following is part of the mbox.h header file.
Click here to download mbox.h.
#include <thread.h> #include <synch.h> typedef struct mmBox { int Data; sema_t NotFull; sema_t NotEmpty; } mbox_t; int msg_init(mbox_t *); int msg_send(mbox_t *, int *); int msg_receive(mbox_t *, int *);
The following is the implementation file mbox.c. Please compare it with the general implementation of bounded buffer discussed earlier.
Click here to download mbox.c.
#include <thread.h> #include <synch.h> #include "mbox.h" int msg_init(mbox_t *MailBox) { sema_init(&(MailBox->NotFull), 1, USYNC_THREAD, (void *) NULL); sema_init(&(MailBox->NotEmpty), 0, USYNC_THREAD, (void *) NULL); MailBox->Data = 0; return (0); } int msg_send(mbox_t *MailBox, int *Value) { sema_wait(&(MailBox->NotFull)); MailBox->Data = *Value; sema_post(&(MailBox->NotEmpty)); return (*Value); } int msg_receive(mbox_t *MailBox, int *Value) { sema_wait(&(MailBox->NotEmpty)); *Value = MailBox->Data; sema_post(&(MailBox->NotFull)); return (*Value); }