1
0
mirror of https://github.com/danog/libtgvoip.git synced 2024-12-02 17:51:06 +01:00
libtgvoip/BlockingQueue.cpp

77 lines
1.4 KiB
C++
Raw Normal View History

2017-02-02 17:24:40 +01:00
//
// libtgvoip is free and unencumbered public domain software.
// For more information, see http://unlicense.org or the UNLICENSE file
// you should have received with this source code distribution.
//
#include "BlockingQueue.h"
using namespace tgvoip;
BlockingQueue::BlockingQueue(size_t capacity) : semaphore(capacity, 0){
2017-02-02 17:24:40 +01:00
this->capacity=capacity;
2017-03-30 16:06:59 +02:00
overflowCallback=NULL;
2017-02-02 17:24:40 +01:00
init_mutex(mutex);
}
BlockingQueue::~BlockingQueue(){
semaphore.Release();
2017-02-02 17:24:40 +01:00
free_mutex(mutex);
}
void BlockingQueue::Put(void *thing){
MutexGuard sync(mutex);
2017-02-02 17:24:40 +01:00
queue.push_back(thing);
bool didOverflow=false;
2017-02-02 17:24:40 +01:00
while(queue.size()>capacity){
didOverflow=true;
2017-03-30 16:06:59 +02:00
if(overflowCallback){
overflowCallback(queue.front());
queue.pop_front();
}else{
abort();
}
2017-02-02 17:24:40 +01:00
}
if(!didOverflow)
semaphore.Release();
2017-02-02 17:24:40 +01:00
}
void *BlockingQueue::GetBlocking(){
semaphore.Acquire();
MutexGuard sync(mutex);
2017-02-02 17:24:40 +01:00
void* r=GetInternal();
return r;
}
void *BlockingQueue::Get(){
MutexGuard sync(mutex);
if(queue.size()>0)
semaphore.Acquire();
2017-02-02 17:24:40 +01:00
void* r=GetInternal();
return r;
}
void *BlockingQueue::GetInternal(){
2017-02-02 17:24:40 +01:00
if(queue.size()==0)
return NULL;
void* r=queue.front();
queue.pop_front();
return r;
}
unsigned int BlockingQueue::Size(){
2017-02-02 17:24:40 +01:00
return queue.size();
}
void BlockingQueue::PrepareDealloc(){
2017-02-02 17:24:40 +01:00
}
2017-03-30 16:06:59 +02:00
void BlockingQueue::SetOverflowCallback(void (*overflowCallback)(void *)){
2017-03-30 16:06:59 +02:00
this->overflowCallback=overflowCallback;
}