Provide a semaphore class.
More...
Namespaces |
namespace | bslmt |
Detailed Description
- Outline
-
-
- Purpose:
- Provide a semaphore class.
-
- Classes:
-
- See also:
- Component bslmt_timedsemaphore
-
- Description:
- This component defines a portable and efficient thread synchronization primitive. In particular,
bslmt::Semaphore
is an efficient synchronization primitive that enables sharing of a counted number of resources or exclusive access. The usage model of this facility is modeled on POSIX semaphores and Windows semaphores.
-
- Usage:
- This example illustrates a very simple queue where potential clients can push integers to a queue, and later retrieve the integer values from the queue in FIFO order. It illustrates two potential uses of semaphores: to enforce exclusive access, and to allow resource sharing. Note that the
IntQueue
constructor increments the count of the semaphore to 1 so that values can be pushed into the queue immediately following construction:
IntQueue::IntQueue(bslma::Allocator *basicAllocator)
: d_queue(basicAllocator)
{
d_mutexSem.post();
}
IntQueue::~IntQueue()
{
d_mutexSem.wait();
}
int IntQueue::getInt()
{
d_resourceSem.wait();
d_mutexSem.wait();
const int ret = d_queue.back();
d_queue.pop_back();
d_mutexSem.post();
return ret;
}
void IntQueue::pushInt(int value)
{
d_mutexSem.wait();
d_queue.push_front(value);
d_mutexSem.post();
d_resourceSem.post();
}