Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

A counting semaphore is used when elements of a resource can be used by more than one task at the same time. For example, a counting semaphore is used in the management of a buffer pool, as shown in Figure 13-3. Let’s the figure below. Let’s assume that the buffer pool initially contains 10 buffers. A task obtains a buffer from the buffer manager by calling BufReq(). When the buffer is no longer needed, the task returns the buffer to the buffer manager by calling BufRel(). The pseudo-code for these functions is shown in Listing 13-9the listing that follows the figure below.

The buffer manager satisfies the ?rst first 10 buffer requests because the semaphore is initialized to 10. When all buffers are used, a task requesting a buffer is suspended until a buffer becomes available. You use µC/OS-III’s OSMemGet() and OSMemPut() (see Memory Management API Changes) to obtain a buffer from the buffer pool. When a task is finished with the buffer it acquired, the task calls BufRel() to return the buffer to the buffer manager and the buffer is inserted into the linked list before the semaphore is signaled. By encapsulating the interface to the buffer manager in BufReq() and BufRel(), the caller does not need to be concerned with actual implementation details.

Listing 13-9 Buffer management using a semaphore.

Note that the details of creating the memory partition are removed since this is discussed in Memory Management API Changes. The semaphore is used here to extend the memory management capabilities of µC/OS-III, and to provide it with a blocking mechanism. However, only tasks can make BufReq() and BufRel() calls.