Slide 1 Slide 2 Slide 3 Slide 4 Slide 5 Slide 6 Slide 7 Slide 8 Slide 9 Slide 10 Slide 11 Product List
SYS/BIOS Semaphores Slide 7

To give one a more concrete demonstration of how a binary semaphore is used, TI is going to walk through this very short code excerpt. The main idea here is that a binary semaphore can be used to protect a critical resource or section, something that more than one process or thread will want to access, and one needs to make sure that only one accesses it at any given instant in time. A good analogy for this are automobiles driving on a road. Each auto represents an independent task and as long as all the tasks are driving on their own roads, there will not be a problem. But if the roads cross, that intersection is a critical section and only one car can be allowed in it at a time, or disaster will strike. Roads have stop lights to protect critical sections, but in programming one uses binary semaphores to do the same thing. In this code example, there are two tasks running concurrently, but at different priorities. When created, the low priority task will be made ready to run and the high priority task will start executing. It enters an infinite loop and needs to perform an operation on a critical resource, a global variable, that is shared between the two tasks. So before operating on the resource, the task first pends on a semaphore and then posts the semaphore when it is done. When the high priority task goes to sleep for several milliseconds, the low priority task gets its chance to run and operate on the resource, also bracketing the operation with a pend and a post. When the high priority task wakes back up, it will immediately pend on the semaphore again. If the low priority task was interrupted while in the critical section, this pend will make the high priority task block, allowing the low priority task to finish the operation. As soon as the low priority task posts the semaphore, the high priority task will resume running.

PTM Published on: 2012-07-19