Skip to content

Commit

Permalink
factor out a common function
Browse files Browse the repository at this point in the history
  • Loading branch information
nickbroon committed Feb 14, 2018
1 parent cebc685 commit c0b4e79
Showing 1 changed file with 21 additions and 46 deletions.
67 changes: 21 additions & 46 deletions src/common/ConcurrentQueue.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,24 @@
template<class T>
class ConcurrentQueue
{
private:

inline bool do_pop(T* res)
{
lock.lock();
*res = queue.front();
queue.pop();
poppedCount++;
count--;
lock.unlock();

pushSemaphore.post();

DPRINTF_DEBUG( "(%s) element popped", ownerName.c_str());

return true;
}

public:
/**
* default queue size
Expand Down Expand Up @@ -75,76 +93,33 @@ class ConcurrentQueue

inline bool pop(T* res)
{
DPRINTF_DEBUG( "(%s) trying to pop element (%d elements in queue)",
(ownerName.empty() ? "<owner not set>" : ownerName.c_str()),
maxEntries-pushSemaphore.getCount());
if (!popSemaphore.wait()) {
return false;
}

lock.lock();
*res = queue.front();
queue.pop();
poppedCount++;
count--;
lock.unlock();

pushSemaphore.post();

DPRINTF_DEBUG( "(%s) element popped", ownerName.c_str());

return true;
return do_pop(res);
};

// try to pop an entry from the queue before timeout occurs
// if successful, res will hold the popped entry and true will be returned
// of the timeout has been reached, res will be set to NULL and false will be returned
inline bool pop(long timeout_ms, T *res)
{
// try to get an item from the queue
if(!popSemaphore.wait(timeout_ms)) {
// timeout occured
return false;
}

// popSemaphore.wait() succeeded, now pop the frontmost element
lock.lock();
*res = queue.front();
queue.pop();
poppedCount++;
count--;
lock.unlock();

pushSemaphore.post();

DPRINTF_DEBUG( "(%s) element popped", ownerName.c_str());

return true;
return do_pop(res);
}

// like pop above, but with absolute time instead of delta.
// use this instead of the above, makes things easier!
inline bool popAbs(const struct timespec& timeout, T *res)
{
if (popSemaphore.waitAbs(timeout)) {
// popSemaphore.wait() succeeded, now pop the frontmost element
lock.lock();
*res = queue.front();
queue.pop();
poppedCount++;
count--;
lock.unlock();

pushSemaphore.post();

DPRINTF_DEBUG( "(%s) element popped", ownerName.c_str());

return true;
return do_pop(res);
}
else {
// timeout occured
*res = 0;

return false;
}
}
Expand Down

0 comments on commit c0b4e79

Please sign in to comment.