Skip to content
Snippets Groups Projects
Commit c6869416 authored by Rainer Kartmann's avatar Rainer Kartmann
Browse files

Add CountingSemaphore

parent 3d172d48
No related branches found
No related tags found
No related merge requests found
......@@ -88,6 +88,7 @@ SET(SOURCES
shapes/json_conversions.cpp
threads/system_thread_id.cpp
threads/CountingSemaphore.cpp
)
SET(INCLUDES
......@@ -256,6 +257,7 @@ SET(INCLUDES
backport/span/gcc_header.h
threads/system_thread_id.h
threads/CountingSemaphore.h
)
simox_generate_subdir_headers(
......
......@@ -2,4 +2,5 @@
// This file is generated!
#include "threads/CountingSemaphore.h"
#include "threads/system_thread_id.h"
#include "CountingSemaphore.h"
namespace simox::threads
{
CountingSemaphore::CountingSemaphore()
{}
CountingSemaphore::CountingSemaphore(unsigned int count) : _count(count)
{}
void CountingSemaphore::notify()
{
std::lock_guard<std::mutex> lock(_mutex);
++_count;
_condition.notify_one();
}
void CountingSemaphore::wait()
{
std::unique_lock<std::mutex> lock(_mutex);
_condition.wait(lock, [this]()
{
return _count > 0;
});
--_count;
}
bool CountingSemaphore::try_wait()
{
std::unique_lock<std::mutex> lock(_mutex);
if (_count > 0)
{
--_count;
return true;
}
return false;
}
}
#pragma once
#include <condition_variable>
#include <mutex>
namespace simox::threads
{
/**
* @brief A counting semaphore.
*
* Threads can enter when the internal count is > 0.
* Notifiying the semaphore increments the count and allows threads to enter.
* A thread can wait until it may enter. When it enters, it decrements
* the internal count.
*
* Can be used e.g. in a Producer-Consumer pattern.
* The producer signals new jobs via `notify()`, while the consumer waits
* for new jobs via `wait()`.
*/
class CountingSemaphore
{
public:
/// Construct an initially blocking semaphore (initial count 0).
CountingSemaphore();
/// Construct a semaphore with the given count.
CountingSemaphore(unsigned int count);
/**
* @brief Signal that one waiting thread may continue.
* Also known as `post()` or `signal()`.
*/
void notify();
/**
* @brief Wait until a thread may enter.
*/
void wait();
/**
* @brief Try to enter. If the semaphore is currently blocking, return false.
* @return True if entering was successful, false if semaphore was blocking.
*/
bool try_wait();
private:
/// The mutex for _condition and _count.
std::mutex _mutex;
/// The condition variable to wake up waking threads.
std::condition_variable _condition;
/// The current count. Waiting threads may enter when > 0.
unsigned int _count = 0;
};
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment