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