Page 413 - Programming Microcontrollers in C
P. 413

398    Chapter 8  MCORE, A RISC Machine

                          read the contents of the semaphore and then, if it is in the proper
                          condition, it will be set. Interrupts can come asynchronously at any
                          time. Suppose that in the process of attaching a semaphore, the status
                          of the interrupt is read to be tested, and, prior to marking the semaphore
                          as used, an interrupt occurs. Within this interrupt routine, it also could
                          require an interrupt. In this case, the interrupt that was being processed
                          by the earlier routine will seem to be available, but it is not. In fact
                          when control is returned to the initial portion of the program, the
                          semaphore will be again marked as busy, and now two completely
                          different processes will both assume control over the same semaphore.

                   /* A call to attach_semaphore(‘a’) will attempt to attach
                       safely a semaphore. If a semaphore can be attached, a
                       semaphore number will be returned. Otherwise, a -1 is
                       returned and no semaphore can now be attached. When
                       attach_semaphore(n), where 0<=n<10, is executed, an
                       attempt is made to attach the semaphore specified by the
                       number. If it is not available, a –1 is returned. After
                       the semaphore is attached, use the semaphore number as a
                       parameter on all other semaphore function calls. Function
                       release_semaphore() returns the semaphore to the avail­
                       able semaphore pool. The function semaphore_status()
                       returns TRUE when the semaphore is NOT available, and the
                       function wait_for_semaphore() waits in a tight loop until
                       the semaphore becomes available */

                   #include “mmc2001.h”

                   #define Number_of_semaphores 10
                   #define Minus_one -1

                   /* function prototypes */
                   int attach_semaphore(void);
                   void release_semaphore(int);
                   int semaphore_status(int);
                   void wait_for_semaphore(int);

                   static volatile int semaphore[Number_of_semaphores];
                   int save;

                   int attach_semaphore(int r)
                   {
                       int i;
   408   409   410   411   412   413   414   415   416   417   418