Using a counting semaphore

The following example shows how to use a counting semaphore object to start a few tasks in the same time.

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


#define TASK_COUNT  10
#define SEM_NAME    "Sem1"


ERROR Task(PVOID Arg)
{
  BOOL PrevLockState;
  HANDLE SemaphoreHandle;

  /* Print task startup message */
  printf("Task%i started.\n", (int) Arg);

  /* Create semaphore */
  SemaphoreHandle = osOpenCountSem(SEM_NAME);

  /* Wait for semaphore to start all tasks in these same time */
  osWaitForObject(SemaphoreHandle, OS_INFINITE);

  /* Print task finish message */
  PrevLockState = arLock();
  printf("Task%i finishes work.\n", (int) Arg);
  arRestore(PrevLockState);
  return ERR_NO_ERROR;
}


ERROR MainTask(PVOID Arg)
{
  int i;
  HANDLE SemaphoreHandle;     

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

  /* Create non-signaled semaphore */
  SemaphoreHandle = osCreateCountSem(SEM_NAME, 0, TASK_COUNT);

  /* Create tasks with priority higher than priority of current task. The new
     task will be started immediately */
  for(i = 0; i < TASK_COUNT; i++)
    osCreateTask(Task, (PVOID) i, 0, 0, FALSE);

  /* Wait for one second */
  printf("Wait for one second...\n");
  osSleep(AR_TICKS_PER_SECOND);

  /* Release semaphore. All tasks waiting for will run immediately.
     Modifying the ReleaseCount parameter will affect to number of released
     tasks */
  osReleaseCountSem(SemaphoreHandle, TASK_COUNT, NULL);

  /* This message will be printed when all tasks are terminated */
  printf("All tasks has been ended.\n");
  return ERR_NO_ERROR;
}


int main(void)
{
  /* Initialization */
  arInit();
  stInit();
  osInit();

  /* Create main task */
  osCreateTask(MainTask, NULL, 0, 1, FALSE);

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

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

The result on the console should look as follows:

Task0 started.
Task1 started.
Task2 started.
Task3 started.
Task4 started.
Task5 started.
Task6 started.
Task7 started.
Task8 started.
Task9 started.
Wait for one second...
Task0 finishes work.
Task1 finishes work.
Task2 finishes work.
Task3 finishes work.
Task4 finishes work.
Task5 finishes work.
Task6 finishes work.
Task7 finishes work.
Task8 finishes work.
Task9 finishes work.
All tasks have been ended.
SpaceShadow documentation