The following example demonstrates the implementation of the osPrintf function, a thread-safe equivalent to the standard C printf function. The osPrintf function is specifically designed to be accessed concurrently by multiple tasks within the system.
#include <stdio.h> #include <stdarg.h> #include "OS_API.h" #define TASK_COUNT 8 HANDLE PrintMutexHandle; void osPrintf(char *Message, ...) { va_list ap; /* Wait for mutex */ osWaitForObject(PrintMutexHandle, OS_INFINITE); /* Print string on the console or send it via RS-232 */ va_start(ap, Message); vprintf(Message, ap); va_end(ap); /* Release mutex */ osReleaseMutex(PrintMutexHandle); } ERROR WorkerTask(PVOID Arg) { /* Mark parameter as unused */ AR_UNUSED_PARAM(Arg); /* Print messages */ while(1) osPrintf("Task %i prints message.\n", (int) Arg); } int main(void) { int i; /* Initialization */ arInit(); stInit(); osInit(); /* Create mutex for printf function */ PrintMutexHandle = osCreateMutex(NULL, FALSE); /* Create sender tasks */ for(i = 0; i < TASK_COUNT; i++) osCreateTask(WorkerTask, (PVOID) (i + 1), 0, 0, FALSE); /* Start the operating system */ osStart(); /* Deinitialization */ osDeinit(); arDeinit(); return 0; }