/* ========================================================================
 *                          BoundedBuffer.cpp
 * ------------------------------------------------------------------------
 *  Implementation file for the BoundedBuffer class.
 *
 *  Copyright 1997-1998 by G. Wade Johnson (Telescan, Inc.)
 *   Use of this code is placed in the public domain as long as the
 *   copyright notice is retained.
 */

#include "BoundedBuffer.h"
#include "CriticalSection.h"
#include "Semaphore.h"
#include <string>
#include <windows.h>




BoundedBuffer::BoundedBuffer( short size )
 : myBufferSize(size), myName(""),
   mypBufferMutex(0), mypFullSem(0), mypEmptySem(0)
 {
  mypBufferMutex = new CriticalSection();
  mypFullSem     = new Semaphore(size,size);
  mypEmptySem    = new Semaphore(0,size);
 }




BoundedBuffer::BoundedBuffer( short size, const char *name )
 : myBufferSize(size), myName(name),
   mypBufferMutex(0), mypFullSem(0), mypEmptySem(0)
 {
  mypBufferMutex = new CriticalSection();
  mypFullSem     = new Semaphore( size, size, (myName+"Full").c_str() );
  mypEmptySem    = new Semaphore( 0, size, (myName+"Empty").c_str() );
 }




BoundedBuffer::~BoundedBuffer()
 {
  delete mypBufferMutex;
  mypBufferMutex = 0;

  delete mypFullSem;
  mypFullSem = 0;

  delete mypEmptySem;
  mypEmptySem = 0;
 }


void   BoundedBuffer::BeginGet()
 {
  mypEmptySem->Wait();
  mypBufferMutex->Wait();
 }


void   BoundedBuffer::EndGet()
 {
  mypFullSem->Release();
  mypBufferMutex->Release();
 }


void   BoundedBuffer::BeginPut()
 {
  mypFullSem->Wait();
  mypBufferMutex->Wait();
 }


void   BoundedBuffer::EndPut()
 {
  mypEmptySem->Release();
  mypBufferMutex->Release();
 }

