Implementing a Monitor

Minas Mina minas_mina1990 at hotmail.co.uk
Fri Jul 27 14:31:32 PDT 2012


I'm using condition variables to implement a monitor that 
simulates the producer-consumer(unbounded buffer) scenario.

Note:
monitor is __gshared and is initialized in main(). Then the other 
threads are created and run.

There is one producer thread, and 5 consumer threads.

void producer()
{
	while( 1 )
	{
		monitor.produce();
	}
}

void consumer()
{
	while( 1 )
	{
		monitor.consume();
	}
}

class Monitor
{
	Cond cond;
	
	char[] buffer;
	ulong sz;
	
	this()
	{
		// necessary: The condition variable constructor requires a 
mutex passed to it
		cond = new Cond(new Mutex());
	}
	
	void produce()
	{
		// produce a letter a-z
		char c = 'a' + rand() % 26;
		writeln("* Producer: Produced a '", c, "' buffer.length = ", 
buffer.length, "\n");
		
		// 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()
	{
		if( buffer.length == 0 )
		{
			writeln("put to sleep");
			cwait(cond); // calls Condition.wait()
		}
		
		// take
		char c = buffer[buffer.length-1];
		--buffer.length;
		
		writeln("# Consumer has taken a '", c, "' buffer = [", buffer, 
"] (", buffer.length, " elements)\n");
	}
}





The output is something like:
put to sleep
put to sleep
put to sleep
put to sleep
* Producer: Produced a 'n' buffer.length = 0

put to sleep
* Producer: Produced a 'w' buffer.length = 1

* Producer: Produced a 'l' buffer.length = 2

* Producer: Produced a 'r' buffer.length = 3

* Producer: Produced a 'b' buffer.length = 4

* Producer: Produced a 'b' buffer.length = 5

* Producer: Produced a 'm' buffer.length = 6

* Producer: Produced a 'q' buffer.length = 7

...

Even though the producer calls notify() when he finishes, none of 
the consumer threads is ever resumed... (I ran the program for a 
while and redirected output to a file. Then I searched for "#" 
that the consumer prints but nothing).

Why is that happening? Is there something wrong with 
Condition.notify()?

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

Thanks


More information about the Digitalmars-d-learn mailing list