Walter is right about transitive readonly - here's the alternative

Janice Caron caron800 at googlemail.com
Thu Sep 13 09:33:50 PDT 2007


On 9/13/07, Sean Kelly <sean at f4.ca> wrote:
> What if I only plan to use the class within a single thread and don't
> want to pay for the cost of a lock?

Interesting question. In C++, I would have said, if you only want
single-threaded, don't bother with thread-safety. It's only an issue
here because it looks like we're being told, you /must/ be
thread-safe.

I think the answer would have to be, write /as if/ multithreaded, and
then compile with a special compiler option (--singlethreaded or
something). That compiler option would throw away all the locking and
reduce it to nothing, so zero performance impact. That would be my
guess, anyway.

Someone else suggested (in another thread, I think) some way of
telling the D compiler "I want to be thread-unsafe" as part of the
D-language itself. I don't know how that would work, but maybe
something like

 unsafe
 {
     /* code */
 }

I don't think Walter would buy it though. I think the compiler option
would be the way to go.


> Also, how would this apply to a
> linked-list container?  Would each node have to be shared and thus have
> its own lock, or would the outermost one suffice?

Things like that are totally up to the class designer, but if you
think of it in old-fashioned terms (manual mutex locking), you'd most
likely want to have one single mutex that controls access to the
entire list. That's what I'd do. You could have smaller granularity if
you want, but I'd go with one per list.

It's not obvious how to express that in code, however! I guess it
would be something like:

class List
{
    void InsertBefore(Node * next, Node * newNode);
    /* etc */
}

shared List shared_list;

scope list = writable(shared_list);
list.insertBefore(next, newNode);

In that example, "this" is being passed around - and it appears
unneccesary. (You'd think insertBefore() could be static) But of
course, it actually /is/ necessary to pass "this" around, because
that's where the mutex is.

There's lots of other ways of doing it, of course. Like I said, it's a
programmers' choice, and you can have as much or as little granularity
with what the share includes as you choose.



More information about the Digitalmars-d mailing list