Semaphores
Thread Scheduling 4-61
Example 4-11. SEM Example Using Three Writer Tasks
/*
* ======== semtest.c ========
*
* Use a QUE queue and SEM semaphore to send messages from
* multiple writer() tasks to a single reader() task. The
* reader task, the three writer tasks, queues, and semaphore
* are created statically.
*
* The MsgObj’s are preallocated in main(), and put on the
* free queue. The writer tasks get free message structures
* from the free queue, write the message, and then put the
* message structure onto the message queue.
* This example builds on quetest.c. The major differences are:
* - one reader() and multiple writer() tasks.
* - SEM_pend() and SEM_post() are used to synchronize
* access to the message queue.
* - ‘id’ field was added to MsgObj to specify writer()
* task id.
*
* Unlike a mailbox, a queue can hold an arbitrary number of
* messages or elements. Each message must, however, be a
* structure with a QUE_Elem as its first field.
*/
#include <std.h>
#include <log.h>
#include <mem.h>
#include <que.h>
#include <sem.h>
#include <sys.h>
#include <tsk.h>
#include <trc.h>
#define NUMMSGS 3 /* number of messages */
#define NUMWRITERS 3 /* number of writer tasks created with */
/* Config Tool */
typedef struct MsgObj {
QUE_Elem elem; /* first field for QUE */
Int id; /* writer task id */
Char val; /* message value */
} MsgObj, *Msg;
Void reader();
Void writer();
/*
* The following objects are created statically.
*/
extern SEM_Obj sem;
extern QUE_Obj msgQueue;
extern QUE_Obj freeQueue;
extern LOG_Obj trace