Walter is right about transitive readonly - here's the alternative
Steven Schveighoffer
schveiguy at yahoo.com
Thu Sep 13 09:26:36 PDT 2007
"Sean Kelly" wrote
> Regan Heath wrote:
> >
>> Does it 'break' the system to allow a thread with a read lock to aquire a
>> write lock (assuming we block until no other thread has a read lock)?
>
> Some read-write locks allow a read lock to be 'upgraded' to a write lock,
> but I never liked the idea. For one, it complicates the algorithm quite a
> bit.
There is no problem with upgrading, the problem is the assumption that the
data has not changed since you have obtained the write lock. Janice's code
is a good example. Let's say we change it to:
class Lookup
{
shared int[int] map_s;
int readonly lookup(int key)
{
{
auto map = readable(map_s);
if (key in map) return map[key];
//} no release of readable lock yet.
//{
auto map = writable(map_s);
//if (key in map) return map[key]; // uncomment this for
thread safety
map[key] = readDataFromFile(key);
return map[key];
}
}
}
And you have 2 threads running, both are simultaneously executing this code.
If they both have a read lock, and want to upgrade to a write lock, who gets
it first? Whoever does, once the first thread has released the lock, the
second thread now gets the lock AFTER the data is modified. There's no way
around it.
Basically, you can *upgrade*, but you can't be certain that the data didn't
change. You may be able to do something funky like return a special flag if
you are the *first* thread to get the upgrade, but I think the added
overhead is not going to be worth it, and the coder may assume that since
they upgraded, the data didn't change, until they read the documentation (2
weeks later after chasing down some obscure thread bug).
BTW, Janice, I like your idea, I think it should be added.
-Steve
More information about the Digitalmars-d
mailing list