Added additional poll method without timeout

This commit is contained in:
2 changed files with 54 additions and 6 deletions

View File

@@ -136,9 +136,11 @@ public:
*
* @param timeoutMs how long to wait before giving up, in milliseconds
* @param defaultVal value, which returns if the specified waiting time elapses before an element is available
* @param isOk flag, which indicates result of method execution. It will be set to false if timeout, or true if
* return value is retrieved value
* @return the head of this queue, or defaultVal if the specified waiting time elapses before an element is available
*/
T poll(int timeoutMs, const T & defaultVal, bool* isOk = nullptr) {
T poll(int timeoutMs, const T & defaultVal = T(), bool* isOk = nullptr) {
T t;
mutex.lock();
bool isNotEmpty = cond_var_add->waitFor(mutex, timeoutMs, [&]() { return !PIDeque<T>::isEmpty(); });
@@ -149,6 +151,26 @@ public:
return t;
}
/**
* @brief Retrieves and removes the head of this queue and return it if queue not empty, otherwise return defaultVal.
* Do it immediately without waiting.
*
* @param defaultVal value, which returns if the specified waiting time elapses before an element is available
* @param isOk flag, which indicates result of method execution. It will be set to false if timeout, or true if
* return value is retrieved value
* @return the head of this queue, or defaultVal if the specified waiting time elapses before an element is available
*/
T poll(const T & defaultVal = T(), bool* isOk = nullptr) {
T t;
mutex.lock();
bool isNotEmpty = !PIDeque<T>::isEmpty();
t = isNotEmpty ? T(PIDeque<T>::take_front()) : defaultVal;
mutex.unlock();
if (isNotEmpty) cond_var_rem->notifyOne();
if (isOk != nullptr) *isOk = isNotEmpty;
return t;
}
/**
* @brief Returns the number of elements that this queue can ideally (in the absence of memory or resource
* constraints) contains. This is always equal to the initial capacity of this queue less the current size of this queue.