Created
December 10, 2014 14:11
-
-
Save jeff-hager-dev/333c49ae523fbed2da30 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*============================================================================= | |
Description: A thread safe queue using boost::mutex library to do so. | |
Author: J. Nolan Hager (JNHager) | |
NOTE (JNhager): boost::mutext::scoped_lock locks all resources in the same | |
scope until that scope has resolved. This means all scopes within will be | |
locked as well. | |
=============================================================================*/ | |
#ifndef _ObjQueue_ | |
#define _ObjQueue_ | |
#include <iostream> | |
#include <string> | |
#include <queue> | |
#include "boost/thread.hpp" | |
#include "boost/thread/mutex.hpp" | |
using namespace std; | |
namespace objQueue | |
{ | |
template <typename objData> | |
class ObjQueue | |
{ | |
private: | |
std::queue<objData> _threadQueue; | |
mutable boost::mutex _qMutex; | |
boost::condition_variable conditionVar; | |
int _maxItemCount; | |
int _itemCount; | |
public: | |
ObjQueue() | |
{ | |
_maxItemCount = -1; | |
_itemCount = 0; | |
}; | |
ObjQueue(int maxItemCount) | |
{ | |
_maxItemCount = maxItemCount; | |
_itemCount = 0; | |
} | |
~ObjQueue(){}; | |
bool empty() const | |
{ | |
boost::mutex::scoped_lock lock(_qMutex); | |
return _threadQueue.empty(); | |
} | |
//NOTE (JNHager): This will return false till the queue has an item. This will allow | |
// this class to be used with multiple threads and not sleeping them all. | |
bool pop(objData& data) | |
{ | |
boost::mutex::scoped_lock lock(_qMutex); | |
if(_threadQueue.empty()) { return false; } | |
data = _threadQueue.front(); | |
_threadQueue.pop(); | |
_itemCount--; | |
return true; | |
} | |
int count() const | |
{ | |
boost::mutex::scoped_lock lock(_qMutex); | |
return _itemCount; | |
} | |
bool push(objData data) | |
{ | |
boost::mutex::scoped_lock lock(_qMutex); | |
if(_maxItemCount == -1 || _itemCount < _maxItemCount){ | |
_threadQueue.push(data); | |
_itemCount ++; | |
return 1; | |
} | |
return 0; | |
} | |
}; | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment