Idea for Threads

Martin Persenius martin at persenius.net
Sun May 13 08:47:04 PDT 2007


Thomas Kuehne Wrote:
> Most likely some restrictions are missing but this should give you an
> idea.
> 
> Thomas

I have been thinking about this a bit and have a couple of ideas to play with. I want to test one with you.

One of the problems is memory corruption because reading is done when a write is in progress. This can be avoided by the use of mutexes. I think this should be automated through the use of protected types, which would give the programmer less to think about. The lock needs to be effective for both reads and writes, but only writes need to lock. Already objects have a mutex upon creation (read it in a post from 2006), this could be used for the protected types as such:

1. Before reading, check if it is locked, then wait or read.
2. Before writing, acquire lock, write, release.

The protected types could be the regular names suffixed with _p (e.g. uint_p. Now, this doesn't solve all issues that could result from the use of pointers, but if you just avoid that, automatic locking would at least simplify the matter. I think this sounds like a pretty straightforward idea, so I'd be happy to hear any outstanding objections. (it would benefit from having structs capable of opAssign, or language integration)

Example which always locks... not as fast as only checking lock on read:

private import tango.io.Stdout,
                           tango.util.locks.Mutex;

class Protected(T)
{
	private T item;
	Mutex m;
	
	this()
	{
		m = new Mutex();
	}
	
	void opAssign(T v)
	{
		m.acquire();
		scope(exit) m.release;
		item = v;
	}
	
	T opCall()
	{
		m.acquire();
		scope(exit) m.release();
		return item;
	}
}

int main()
{
	auto x = new Protected!(int);
	
	x = 5;
	
	Stdout.formatln("x.item = {0}", x());
	
	return 0;
}



More information about the Digitalmars-d mailing list