synchronized confusion...

Ali Çehreli acehreli at yahoo.com
Tue Apr 16 08:38:15 PDT 2013


On 04/15/2013 11:06 PM, estewh wrote:

 > Hi All,
 >
 > I have this bit of code like this:
 >
 > shared bool varInitialized = false;
 > bool initVar() {
 >     bool ret;
 >     synchronized { ret = varInitialized;}
 >     return ret;
 > }
 >
 > I know there are atomics and I am using them but I am curious about the
 > above code. It compiles but I have no idea how safe it is.

That synchronized block is protected in the sense that only a single 
thread will be executing it.

Separate synchronized blocks may be executed at the same time. (There is 
no global lock for all of them.)

If you want to synchronize multiple synchronized blocks, then you must 
use a class object on all of them.

The following is a translated program from one of my 
yet-to-be-translated chapters:

   http://ddili.org/ders/d/es_zamanli_shared.html

import std.stdio;
import std.concurrency;
import core.thread;

class Lock
{}

void incrementor(shared(int) * value, shared Lock lock)
{
     foreach (i; 0 .. 1000) {
         synchronized (lock) {
             ++(*value);
         }
     }
}

void decrementor(shared(int) * value, shared Lock lock)
{
     foreach (i; 0 .. 1000) {
         synchronized (lock) {
             --(*value);
         }
     }
}

void main()
{
     shared Lock lock = new shared(Lock)();
     shared int theVariable = 0;

     foreach (i; 0 .. 100) {
         spawn(&incrementor, &theVariable, lock);
         spawn(&decrementor, &theVariable, lock);
     }

     thread_joinAll();
     writeln("last value: ", theVariable);
}

 > Reading TDPL I got the impression synchronized works only for entire
 > classes. If so why does the above compile and is it thread safe?

I don't know the future plans but synchronized blocks currently work. If 
you give two separate lock objects to incrementor() and decrementor() 
you will see that the last value will rarely be zero.

And the idea is that std.parallelism and std.concurrency should be 
sufficient for most needs.

 >
 > Thanks for any help
 >
 > Cheers,
 > Stewart
 >

Ali

-- 
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html



More information about the Digitalmars-d-learn mailing list