Problems with Mutex

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Oct 27 06:24:13 PDT 2014


On 10/26/14 7:13 PM, ketmar via Digitalmars-d-learn wrote:
> On Sun, 26 Oct 2014 22:53:07 +0000
> Neven via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> wrote:
>
>> Why cannot I globally have auto mutex = new Mutex? And why it
>> works now when I put __gshared?
> this is because 'auto mutex = new Mutex' is not a global declaration,
> it's thread-local declaration. all D variables are thread-locals by
> default.
>
> i.e. you have one indepented Mutex for each thread. and you initialized
> it only in one thread, all other threads got unitialized Mutex objects.
>
> having thread-locals instead of globals by default can be confusing if
> you missed that in documentation. just use 'shared' or '__gshared' to
> get "real" globals.
>

Just as a followup, for some reason Mutex is not callable as a shared 
object, so you have to make it __gshared.

This is unfortunate, but it is the only way to do it right now. Because 
an actual mutex is thread safe, it is not a problem.

-Steve


More information about the Digitalmars-d-learn mailing list