Efficient Independent Synchronized Blocks? Efficient Independent Synchronized Blocks? multithreading multithreading

Efficient Independent Synchronized Blocks?


If your language supported lightweight threads or Actors, you could always have the updating thread spawn a new a new thread to change each object, where each thread just locks, modifies, and unlocks each object. Then have your updating thread join on all its child threads before returning. This punts the problem to the runtime's schedule, and it's free to schedule those child threads any way it can for best performance.

You could do this in langauges with heavier threads, but the spawn and join might have too much overhead (though thread pooling might mitigate some of this).


I don't know if there's a standard way to do this. However, I would implement this something like the following:

do{    if (!updatedA && mutexA.tryLock())    {        scope(exit) mutexA.unlock();        updateA();        updatedA = true;    }    if (!updatedB && mutexB.tryLock())    {        scope(exit) mutexB.unlock();        updateB();        updatedB = true;    }}while (!(updatedA && updatedB));

Some clever metaprogramming could probably cut down the repetition, but I leave that as an exercise for you.


Sorry if I'm being naive, but do you not just Synchronize on objects to make the concerns independent?

e.g.

public Object lock1 = new Object; // access to resource 1 public Object lock2 = new Object; // access to resource 2updateStructure1() {   synchronized( lock1 ) {      ...   }}updateStructure2() {   synchronized( lock2 ) {     ...   }}