Using a shared memory

The following example shows how to use a shared memory object to exchange data between different tasks.

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


#define SH_MEM_NAME "ShMem1"

struct TShMemBuff
{
  double Angle;
  double Cos;
  double Sin;
};


ERROR WritterTask(PVOID Arg)
{
  HANDLE ShMemHandle;
  struct TShMemBuff FAR *ShMemPtr;

  /* Open the shared memory and receive a memory buffer pointer */
  ShMemHandle = osOpenSharedMemory(SH_MEM_NAME, (PVOID FAR *) &ShMemPtr);

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

  /* Infinite loop */
  while(1)
  {
    /* Acquire the shared memory to synchronize access */
    osWaitForObject(ShMemHandle, OS_INFINITE);

    /* Produce some data */
    ShMemPtr->Angle = ShMemPtr->Angle + 0.01;
    ShMemPtr->Cos = cos(ShMemPtr->Angle * M_PI / 180.);
    ShMemPtr->Sin = sin(ShMemPtr->Angle * M_PI / 180.);

    /* Release the shared memory */
    osReleaseSharedMemory(ShMemHandle);
  }
}


ERROR ReaderTask(PVOID Arg)
{
  HANDLE ShMemHandle;
  struct TShMemBuff FAR *ShMemPtr;

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

  /* Open the shared memory and receive a memory buffer pointer */
  ShMemHandle = osOpenSharedMemory(SH_MEM_NAME, (PVOID FAR *) &ShMemPtr);

  /* Infinite loop */
  while(1)
  {
    /* Acquire the shared memory to synchronize access */
    osWaitForObject(ShMemHandle, OS_INFINITE);

    /* Print data stored in the buffer data */
    printf("Angle: %0.4lf\n  Cos: %7.4lf\n  Sin: %7.4lf\n\n",
      ShMemPtr->Angle, ShMemPtr->Cos, ShMemPtr->Sin);

    /* Release the shared memory */
    osReleaseSharedMemory(ShMemHandle);

    /* Sleep for one second */
    osSleep(AR_TICKS_PER_SECOND / 100);
  }
}


int main(void)
{            
  struct TShMemBuff FAR *ShMemPtr;

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

  /* Create tasks */
  osCreateTask(WritterTask, NULL, 0, 0, FALSE);
  osCreateTask(ReaderTask, NULL, 0, 0, FALSE);

  /* Create shared memory object instance and setup the buffer data when it
     is successfully created */
  if(osCreateSharedMemory(SH_MEM_NAME, OS_IPC_PROTECT_EVENT,
    (PVOID FAR *) &ShMemPtr, sizeof(struct TShMemBuff)))
  {
    ShMemPtr->Angle = 0;
    ShMemPtr->Cos = 1;
    ShMemPtr->Sin = 0;
  }

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

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