bounded buffer using semaphores

Hi,
I am trying to build a bounded buffer using counting semaphores in C++.
There are 2 threads using this buffer: a Producer and a Consumer.
My problem is that the consumer continues consuming even when the buffer is empty and thus trying to access buffer[-1], which of course resaults in an exception.

Can anyone help ?
Here is the code:

// Constructor

Airplanes_Buffer::Airplanes_Buffer(int size){

m_Size=size;

m_Counter=0;

m_Buffer=new vector<Aerial_Picture*>;

m_Buffer->resize(size);

m_Mutex = CreateMutex(NULL , FALSE , "MUTEX");// create the mutex

m_Empty_Semaphore = CreateSemaphore(NULL,0,size,"EMPTY");// create empty semaphore

m_Full_Semaphore = CreateSemaphore(NULL,size,size,"FULL");// create full semaphore

}// End constructor

// Destructor;

Airplanes_Buffer::~Airplanes_Buffer(){

vector<Aerial_Picture*>::iterator iter;

for(iter=m_Buffer->begin(); iter != m_Buffer->end(); iter++)

delete (*iter);

delete m_Buffer;

}// End destructor

void Airplanes_Buffer::push(Aerial_Picture* producer_Picture) {

WaitForSingleObject(m_Full_Semaphore,INFINITE);

WaitForSingleObject(m_Mutex,INFINITE);

Aerial_Picture *my_Picture=new Aerial_Picture();// copy into the buffer

my_Picture->copy(producer_Picture);

(*m_Buffer)[m_Counter]=my_Picture;

m_Counter++;

ReleaseMutex(m_Mutex);

ReleaseSemaphore(m_Empty_Semaphore,1,NULL);

}// End push

void Airplanes_Buffer::pop(Aerial_Picture* consumer_Picture) {

WaitForSingleObject(m_Empty_Semaphore,INFINITE);

WaitForSingleObject(m_Mutex,INFINITE);

consumer_Picture->copy((*m_Buffer)[m_Counter-1]);// copy into the consumer

delete (*m_Buffer)[m_Counter-1];// delete from buffer

m_Counter--;

ReleaseMutex(m_Mutex);

ReleaseSemaphore(m_Full_Semaphore,1,NULL);

}// End pop

[3189 byte] By [arazy] at [2008-2-27]
# 1
Hi,
I think the problem is because the WaitForSingleObject first decreases the counter and then waits.
If the Semaphores could have negative values it would have been just fine but Windows Semaphorse are always 0 or bigger.
Roil_O at 2007-8-21 > top of Msdn Tech,.NET Development,.NET Base Class Library...

.NET Development

Site Classified