fix PIThreadPoolExecutor and PIBlockingDequeue

This commit is contained in:
2020-08-11 17:26:44 +03:00
parent dac318c624
commit 8c3349d84a
4 changed files with 27 additions and 69 deletions

View File

@@ -86,29 +86,13 @@ public:
* @param v the element to add
* @return true if the element was added to this queue, else false
*/
bool offer(const T & v) {
bool offer(const T & v, int timeoutMs = 0) {
bool isOk;
mutex.lock();
if (PIDeque<T>::size() >= max_size) {
mutex.unlock();
return false;
}
PIDeque<T>::push_back(v);
mutex.unlock();
cond_var_add->notifyOne();
return true;
}
/**
* @brief Inserts the specified element into this queue, waiting up to the specified wait time if necessary for
* space to become available.
*
* @param v the element to add
* @param timeoutMs how long to wait before giving up, in milliseconds
* @return true if successful, or false if the specified waiting time elapses before space is available
*/
bool offer(const T & v, int timeoutMs) {
mutex.lock();
bool isOk = cond_var_rem->waitFor(mutex, timeoutMs, [&]() { return PIDeque<T>::size() < max_size; } );
if (timeoutMs == 0)
isOk = PIDeque<T>::size() < max_size;
else
isOk = cond_var_rem->waitFor(mutex, timeoutMs, [&]() { return PIDeque<T>::size() < max_size; } );
if (isOk) PIDeque<T>::push_back(v);
mutex.unlock();
if (isOk) cond_var_add->notifyOne();
@@ -140,31 +124,15 @@ public:
* 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 = T(), bool * isOk = nullptr) {
T t;
T poll(int timeoutMs = 0, const T & defaultVal = T(), bool * isOk = nullptr) {
T t = defaultVal;
bool isNotEmpty;
mutex.lock();
bool isNotEmpty = cond_var_add->waitFor(mutex, timeoutMs, [&]() { return !PIDeque<T>::isEmpty(); });
t = isNotEmpty ? T(PIDeque<T>::take_front()) : defaultVal;
mutex.unlock();
if (isNotEmpty) cond_var_rem->notifyOne();
if (isOk) *isOk = isNotEmpty;
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 ? PIDeque<T>::take_front() : defaultVal;
if (timeoutMs == 0)
isNotEmpty = !PIDeque<T>::isEmpty();
else
isNotEmpty = cond_var_add->waitFor(mutex, timeoutMs, [&]() { return !PIDeque<T>::isEmpty(); });
if (isNotEmpty) t = PIDeque<T>::take_front();
mutex.unlock();
if (isNotEmpty) cond_var_rem->notifyOne();
if (isOk) *isOk = isNotEmpty;