Static problem
Stanislav Blinov
stanislav.blinov at gmail.com
Fri Oct 8 02:04:56 PDT 2010
Bob Cowdery wrote:
> On 07/10/2010 21:32, Stanislav Blinov wrote:
>> Steven Schveighoffer wrote:
>>
>>>> What I'd propose is either:
>>>> 1) Create your own lock-free associative array (yup, reinvent the
>>>> wheel to introduce AA to the world of 'shared')
>>>> 2) In this small case it may seem best (though mind that often such
>>>> cases do grow up to the point when you still need to rethink design):
>>>> Make your associative array __gshared and perform synchronization by
>>>> hand, i.e. create a static Mutex (from core.sync.mutex) variable and
>>>> initialize it in your CRegistry's static ctor, and then enclose all
>>>> access to associative array in synchronized(mutex) {} blocks.
>>>>
>>>> Maybe concurrent-programming-in-D guru may propose simpler solution,
>>>> but I don't see another.
>>> FWIW, the classinfo of a class is an object, and as such can be used
>>> as sort of a global lock without having to use a static constructor:
>>>
>>> synchronized(this.classinfo)
>>> {
>>> ....
>>> }
>>>
>>> -Steve
>> Thanks. To my shame, I repeatedly keep forgetting about this.
> Thanks for the suggestions. I'm keen to avoid locks as everything so far
> is message parsing and the system is real-time. Having lots of threads
> that all talk to each other I needed a place to keep the Tid's which is
> accessible to everyone. There is no conflict because the main thread
> creates all others and registers the Tid's. Once the threads go the
> registry is read only. Just setting __gshared makes the app work. This
> may not be good practice I know and I will come back to it when I have
> more time.
>
> I'm not sure how to use synchronized(this.classinfo). Is this in
> combination with __gshared to synchronise access at the method level. Is
> it like a wrapper that goes inside the method?
>
> bob
Yeah, it's like this:
static void register(E_PROC name, Tid tid)
{
synchronized(this.classinfo)
{
theRegistry[name] = tid;
}
}
static Tid getTid(E_PROC name)
{
Tid* result;
synchronized(this.classinfo)
{
result = name in TidRegistry;
}
//...
}
All Objects contain a 'monitor' which is a synchronization primitive.
synchronized(some_object)
{
foo();
}
is similar to
{
some_mutex.lock();
scope(exit) some_mutex.unlock();
// some code
}
More information about the Digitalmars-d-learn
mailing list