Implementing a Monitor

Sean Kelly sean at invisibleduck.org
Mon Jul 30 08:40:09 PDT 2012


You need to lock the mutex to synchronize access to the shared data.

On Jul 27, 2012, at 2:31 PM, Minas Mina <minas_mina1990 at hotmail.co.uk> wrote:
> 
> class Monitor
> {
> 	Cond cond;
           Mutex mutex;

> 	
> 	char[] buffer;
> 	ulong sz;
> 	
> 	this()
> 	{
> 		// necessary: The condition variable constructor requires a mutex passed to it
                   mutex = new Mutex;
                  cond = new Cond(mutex);

> 	}
> 	
> 	void produce()
> 	{
> 		// produce a letter a-z
> 		char c = 'a' + rand() % 26;
> 		writeln("* Producer: Produced a '", c, "' buffer.length = ", buffer.length, "\n");

              synchronized(mutex) {
> 		
> 		// put it into the buffer
> 		++buffer.length;
> 		buffer[buffer.length - 1] = c;
> 		
> 		//if( buffer.length > 1 )
> 		notify(cond); // calls condition.notify()

           }
> 		
> 		//Thread.sleep(dur!"msecs"(1000));
> 	}
> 	
> 	void consume()
> 	{

            synchronized(mutex) {

                   // note changed if to while
> 		while( buffer.length == 0 )
> 		{
> 			writeln("put to sleep");
> 			cwait(cond); // calls Condition.wait()
> 		}
> 		
> 		// take
> 		char c = buffer[buffer.length-1];
> 		--buffer.length;

            }

> Also, is there a function that I can call to immediatly suspend the running thread?

Thread.yield().  Though Cond.wait() will suspend the thread as well.


More information about the Digitalmars-d-learn mailing list