Subj : Re: buffer implementation using semaphores To : comp.programming From : Joe Seigh Date : Sat Sep 17 2005 09:45 am metrix007@yahoo.com wrote: > I have a Semaphore and Buffer class, but I am not sure if I have > implemented it correctly, it is posted here now, I was just after tips > and suggestions..or pointing out erros which are not obvious(to me). > /* > This class implements a bounded buffer that stores Objects and > uses > blocking primitives based on semaphores when the buffer is full > > or > empty. The buffer can be accessed by any number of threads. > */ > public class Buffer > { > > > // ... > // private Object store[] = new Object[size]; > private int inptr = 0; > private int outptr = 0; > private int size = 0; > Semaphore spaces = new Semaphore(size); > Semaphore elements = new Semaphore(0); > > > // creates a bounded buffer with capacity cap > public Buffer() > { > > > } > > > // places the object o in the buffer; if no space is left in > // the buffer, block until a space becomes available > public void put(Object o) > { > spaces.down() ; > // store[inptr] = o ; > inptr = (inptr+1) % size ; > elements.up() ; This won't work for more than one producer. E.g. thread 1: spaces.down(); thread 2: spaces.down(); thread 1: store[inptr] = o; thread 2: store[inptr] = o; // overlays store by thread 1 You're going to lose objects and/or object stores. There are other problems that can occur also. I only gave one example. You could lose the increment of inptr. Etc, etc, ... -- Joe Seigh When you get lemons, you make lemonade. When you get hardware, you make software. .