Using a Mailbox

The following example demonstrates the implementation of a mailbox to facilitate data transfer from multiple producer tasks to a single consumer task responsible for processing the received messages.

#include <stdio.h>
#include <stdarg.h>
#include "OS_API.h"


#define TASK_COUNT          5
#define MAX_STRING_LENGTH   64

HANDLE ConsoleHandle;


ERROR PrintingTask(PVOID Arg)
{
  char String[MAX_STRING_LENGTH];

  /* Mark parameter as unused */
  AR_UNUSED_PARAM(Arg);

  /* Receive messages and print it on the console */
  while(1)
  {
    osMailboxPend(ConsoleHandle, String, sizeof(String));
    printf("%s", String);
  }
}


void MyPrintf(char *Message, ...)
{
  va_list ap;
  char String[MAX_STRING_LENGTH];

  /* Prepare string to send */
  va_start(ap, Message);
  vsprintf(String, Message, ap);
  va_end(ap);

  /* Send whole strings with '\0' character to printing task */
  osMailboxPost(ConsoleHandle, String, stStrLen(String) + 1);
}


ERROR Task(PVOID Arg)
{
  /* Mark parameter as unused */
  AR_UNUSED_PARAM(Arg);

  /* Writing many messages by different tasks is synchronized by mailbox */
  while(1)
    MyPrintf("Task%i is writing.\n", (int) Arg);
}


int main(void)
{
  int i;

  /* Initialization */
  arInit();
  stInit();
  osInit();

  /* Create the mailbox and printing task */
  ConsoleHandle = osCreateMailbox(NULL, OS_IPC_PROTECT_MUTEX |
    OS_IPC_WAIT_IF_EMPTY | OS_IPC_DIRECT_READ_WRITE);
  osCreateTask(PrintingTask, NULL, 0, 0, FALSE);

  /* Create other tasks */
  for(i = 0; i < TASK_COUNT; i++)
    osCreateTask(Task, (PVOID) (i + 1), 0, 0, FALSE);

  /* Start the operating system */
  osStart();

  /* Deinitialization */
  osDeinit();
  arDeinit();
  return 0;
}
SpaceShadow documentation