Idea for Threads
Downs
default_357-line at yahoo.de
Mon May 14 18:12:10 PDT 2007
Sean Kelly wrote:
> Craig Black wrote:
>> I don't know a lot about the details of mutexes. Do they multiple
>> reads simultaneously?
>
> ReadWrite mutexes do, but they're a bit more complicated than your
> average mutex.
About like so?
class extlock {
Thread writing=null;
int reading=0;
int wfwl=0; /// waiting for write lock
private bool lock(bool exclusive)() {
synchronized(this) {
static if (exclusive)
if (writing||(reading>0)) return false; else { writing=Thread.getThis; return true; }
else
if (writing||wfwl) return false; else { reading++; return true; }
}
}
void write_lock() { synchronized(this) wfwl++; while (!lock!(true)) rest; synchronized(this) wfwl--; }
void read_lock() { while (!lock!(false)) rest; }
// the asserts are unsynced because they're not part of the normal flow
// and don't strictly need to be threadsafe.
void write_unlock() { assert(writing==Thread.getThis); synchronized(this) writing=null; }
void read_unlock() { assert(!writing); assert(reading>0); synchronized(this) reading--; }
}
scope class readlock { extlock s; this(typeof(s)s) { this.s=s; s.read_lock; } ~this() { s.read_unlock; } }
scope class writelock { extlock s; this(typeof(s)s) { this.s=s; s.write_lock; } ~this() { s.write_unlock; } }
unittest {
auto sync=new extlock; assert(sync);
sync.read_lock;
sync.read_unlock;
{ scope wl=new writelock(sync); }
}
More information about the Digitalmars-d
mailing list