Problems with Mutex

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Oct 26 17:07:09 PDT 2014


On Sun, 26 Oct 2014 23:37:25 +0000
Neven via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> wrote:

> >Mutex mutex;
> >static this()
> >{
> >  mutex = new Mutex();
> >}
> 
> I have synchronization problems with this one. Even when I 
> prepend __gshared Mutex mutex in this case.
ah, there is another subtle thing. 'static this()' will be called for
each new thread, so what you actually doing is creating new mutex
object when each thread started. it's the same thing as with globals vs
thread-locals. what you really want in this case is 'global
initializer', which will be called once on program startup. to achieve
this you have to write:

  shared static this () {
    mutex = new Mutex();
  }

'shared static this()' will be called only once.

> Thank you for clearing this up. If I understand correctly, 
> __gshared is more of a hack to get C-like global variables, 
> whilst shared is typed shared variable and more preferred?
yes and no. 'shared' is the part of the type, while '__gshared' is not.
i.e.

  shared int a;
  pragma(msg, typeof(a)); // this will print "shared(int)"

  __gshared int b;
  pragma(msg, typeof(b)); // this will print "int"

you can't freely mix shared and non-shared types, so you must cast
'shared' away on occasion and cast it back when necessary. this is not
safe and error-prone.

'__gshared', for the other side, doesn't influence the type, so you can
have global variable which can be passed to other functions without
casting.

but yes, generally this is a hack, and you'd better avoid '__gshared'
in idiomatic D code unless you are really really know what you are
doing and what consequences it may have. ;-)
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20141027/3e25e935/attachment.sig>


More information about the Digitalmars-d-learn mailing list