Home |
RTKernel-32 Programming Manual Multitasking, Real-Time, and RTKernel-32 Mailboxes Alternate APIs for RTKernel-32 |
MailboxesA previous section covered semaphores which can be employed to synchronize tasks, thus providing a mechanism allowing orderly inter-task communication using global data. However, communication via global data is hard to keep track of and error-prone, since a task might "forget" the required semaphore operation before accessing the data. Moreover, no protocol has yet been introduced for a controlled exchange of data. Mailboxes serve to close this gap. A mailbox is a data buffer that can store a fixed number of messages of a fixed size. Tasks can store messages in a mailbox. If the mailbox is full, the task is blocked until space becomes available. Of course, tasks can also retrieve messages from mailboxes. In this case, the task is blocked if no message is available in the mailbox. Any number of tasks can use the same mailbox for storing and retrieving messages. Messages can be appended to a mailbox's message queue using functions RTKPut, RTKPutCond, RTKPutTimed, and RTKPutUntil. Moreover, messages can be inserted at the start of a message queue using functions RTKPutFront, RTKPutFrontCond, RTKPutFrontTimed, and RTKPutFrontUntil. If messages are stored/retrieved in a mailbox using pairs of RTKPut.../RTKGet... function calls, the mailbox will behave as a FIFO buffer (first in, first out), i.e., messages are retrieved from a mailbox in the same sequence as they have been stored. However, if pairs of RTKPutFront.../RTKGet... function calls are used, the mailbox will behave as a LIFO buffer (last in, first out). For maximum flexibility, the RTKPut... and RTKPutFront... functions may be mixed freely, even for the same mailbox. As an example, we can extend the little semaphore demo program for mailboxes. In addition to a signal, data can now be sent to another task: #include <stdio.h> #include <Rtk32.h> RTKMailbox Box; void RTKAPI TaskA(void * P) { int i; printf("Task A: waiting at mailbox\n"); RTKGet(Box, &i); printf("Task A: have received number %i\n", i); } void main(void) { int i; printf("\n"); RTKernelInit(3); Box = RTKCreateMailbox(sizeof(int), 1, "Test Box"); printf("Main : creating task A\n"); RTKCreateThread(TaskA, 4, 0, 0, NULL, "Task A"); printf("Main : please enter a number: "); fflush(stdin); scanf("%i", &i); RTKPut(Box, &i); printf("Main : done.\n"); } The various mailbox related API functions of RTKernel-32 are documented in the RTKernel-32 Reference Manual.
|