| 6 |
| 7 | #ifndef LIBTGVOIP_BLOCKINGQUEUE_H |
| 8 | #define LIBTGVOIP_BLOCKINGQUEUE_H |
| 9 |
| 10 | #include <stdlib.h> |
| 11 | #include <list> |
| 12 | #include "threading.h" |
| 13 | #include "utils.h" |
| 14 |
| 15 | using namespace std; |
| 16 |
| 17 | namespace tgvoip{ |
| 18 |
| 19 | template<typename T> |
| 20 | class BlockingQueue{ |
| 21 | public: |
| 22 | TGVOIP_DISALLOW_COPY_AND_ASSIGN(BlockingQueue); |
| 23 | BlockingQueue(size_t capacity) : semaphore(capacity, 0){ |
| 24 | this->capacity=capacity; |
| 25 | overflowCallback=NULL; |
| 26 | }; |
| 27 |
| 28 | ~BlockingQueue(){ |
| 29 | semaphore.Release(); |
| 30 | } |
| 31 |
| 32 | void Put(T thing){ |
| 33 | MutexGuard sync(mutex); |
| 34 | queue.push_back(std::move(thing)); |
| 35 | bool didOverflow=false; |
| 36 | while(queue.size()>capacity){ |
| 37 | didOverflow=true; |
| 38 | if(overflowCallback){ |
| 39 | overflowCallback(std::move(queue.front())); |
| 40 | queue.pop_front(); |
| 41 | }else{ |
| 42 | abort(); |
| 43 | } |
| 44 | } |
| 45 | if(!didOverflow) |
| 46 | semaphore.Release(); |
| 47 | } |
| 48 |
| 49 | T GetBlocking(){ |
| 50 | semaphore.Acquire(); |
| 51 | MutexGuard sync(mutex); |
| 52 | return GetInternal(); |
| 53 | } |
| 54 |
| 55 | T Get(){ |
| 56 | MutexGuard sync(mutex); |
| 57 | if(queue.size()>0) |
| 58 | semaphore.Acquire(); |
| 59 | return GetInternal(); |
| 60 | } |
| 61 |
| 62 | unsigned int Size(){ |
| 63 | return queue.size(); |
| 64 | } |
| 65 |
| 66 | void PrepareDealloc(){ |
| 67 |
| 68 | } |
| 69 |
| 70 | void SetOverflowCallback(void (*overflowCallback)(T)){ |
| 71 | this->overflowCallback=overflowCallback; |
| 72 | } |
| 73 |
| 74 | private: |
| 75 | T GetInternal(){ |
| 76 | //if(queue.size()==0) |
| 77 | // return NULL; |
| 78 | T r=std::move(queue.front()); |
| 79 | queue.pop_front(); |
| 80 | return r; |
| 81 | } |
| 82 |
| 83 | list<T> queue; |
| 84 | size_t capacity; |
| 85 | //tgvoip_lock_t lock; |
| 86 | Semaphore semaphore; |
| 87 | Mutex mutex; |
| 88 | void (*overflowCallback)(T); |
| 89 | }; |
| 90 | } |
| 91 |
| 92 | #endif //LIBTGVOIP_BLOCKINGQUEUE_H |
| 93 |