Page 388 - ARM Based Microcontroller Projects Using MBED
P. 388

374                             15. Mbed RTOS PROJECTS




















                 FIG. 15.7,  CONT’D
                 variable CNT is defined. Inside the main program variable CNT is cleared to 0 and thread Re-
                 fresh is started. This thread refreshes the display by enabling every digit for 10ms. The main
                 program increments CNT every second and when it reaches 100 it resets back to 0.


                     15.6 Mbed TASK SYNCHRONIZATION—MUTEX, SEMAPHORE,
                                                 AND SIGNALS

                   Mbedprovidesanumberoffunctionsforsynchronizingthreadswhenmultiplethreadsneedto
                 access common global variables. Mutexes and semaphores are used for this purpose. Signals are
                 used to synchronize threads to the occurrence of certain events. For example, an event can be
                 forced to wait for an event to occur and as soon as the event occurs the event can be signaled to
                 continue.Inthissectionweshallbelookingatthemutexes,semaphores,andsignalsinsomedetail.


                 15.6.1 Mutexes
                   Mutexes (or mutual exclusion objects) are programming objects that allow multiple pro-
                 gram threads to share the same resource, such as data or file. A mutex is given a unique name
                 when it is created. The resource is shared in locked by a thread. Once locked, other threads
                 cannot access this resource until it is released by the thread that locked it. Therefore, a mutex
                 is like a lock of a shared resource. A deadlock situation arises if a resource required by other
                 threads are locked and never released by a mutex. A mutex is owned by the thread that uses it
                 to lock the resource and any other thread cannot unlock this mutex. It is important to realize
                 that a mutex locks part of a thread and also any data inside this thread. Mbed functions lock()
                 and unlock() are used to lock and unlock a mutex, respectively.
                   Fig. 15.8 shows an example program (program: Mutex). In this example two threads are
                 created called task1 and task2 which both print messages before and after they run. Without
                 locking the following messages are displayed on the screen:
                   Before 1
                   Before 2
                   After 1
                   After 2
   383   384   385   386   387   388   389   390   391   392   393