Thread Attributes

Jacob Carlborg via Digitalmars-d digitalmars-d at puremagic.com
Sun Jul 13 03:45:28 PDT 2014


On 2014-07-11 19:07, Jonathan Marler wrote:
> I'm not sure how AST macros would assist in thread safety the way that
> this feature would.  Maybe you could elaborate?

Looking at the first example:

@thread:main
int mainThreadGlobal;

@thread:main
int main(string[] args)
{
   // Start the worker thread at some point
}

@thread:worker
void workerLoop()
{
   // do some work , cannot access mainThreadGlobal
}

This would be implemented as a declaration macro [1], something like this:

macro thread (Context, Ast!(string) name, Declaration decl)
{
     if (decl.isVariable)
         decl.attributes ~= Thread(name);

     else if (decl.isCallable)
     {
         foreach (var ; decl.accessedVariables)
         {
             if (auto attr = var.getAttribute!(Thread))
                 if (attr.name != name)
                     context.compiler.error("Cannot access variable with 
thread name " ~ attr.name ~ " from callable with thread name " ~ name);
         }
     }

     return decl;
}

Usage:

@thread("main") int mainThreadGlobal;
@thread("worker") void workerLoop ();

> To explain a little more, when you put a @thread:name or @sync(object)
> attribute on something, the compiler will guarantee that no safe D code
> will ever use that code or data unless it is either on the given thread
> or can guarantee at compile time that it has synchronized on the given
> object.
>
> You mentioned making the variable thread local.  So if I'm
> understanding, you're saying just make it a regular global variable.
> However, the point is that if you tell the compiler that it can only be
> accessed by a single thread then it doesn't need to be thread local.
> Real global variables are preferred over thread local for
> performance/memory reasons.  Their address is known at compile time and
> you don't need to allocate a new instance for every thread.  The only
> reason for thread local variables is to alleviate problems with
> multithreaded applications, but using an attribute like this would allow
> someone to have the benefit of a real global variable without exposing
> it to other threads fixing the synchronization issue.

Makes sense.

[1] http://wiki.dlang.org/DIP50#Declaration_macros

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list