1

Here's what I'm trying to do, with Java:

while(writeSetsIntersect()) {
    wait();
}    
doStuff    
notifyAll();

Here's where I'm stuck: doStuff can be executed concurrently if two threads write to different variables, i.e., they have disjoint write sets. If the write sets intersect, threads need to alternate. So I can't simply put doStuff in a synchronized block, because it's not always (and may never be) necessary.

I could lock the items in the write set, but if two threads with intersecting write sets wait on the same lock, a deadlock could occur. Such as:

Lock[] locks = new Lock[allAvailableVariables.length];
public void getLocks() {
    for(i = 0; i < allAvailableVariables.length; i++)
        if(i is in writeSet)
            locks[i].lock();
}

The easiest way to avoid that (as far as I can come up with) is to synchronize the acquisition of the locks in your write set. But, if two threads with an intersecting write set are vying to get into the synchronization block, a thread with a write set disjoint from the other two would have to wait until they left the sync block.

I guess I could just have a spin lock, but I'd like to avoid that if possible, as evaluating whether the write sets intersect can be expensive.

Does this make any sense at all?

Chance
  • 988
  • 2
  • 13
  • 29

1 Answers1

3

Looks like you want to use lock ordering.

Sort the locks into some kind of natural order. Then lock on each in turn.

Suppose you have locks a and b with a < b. If two threads want to lock both a and b, they will both lock a first. So you can't have a situation where a thread has locked b and is blocked on a, whilst another thread has locked a is blocked on b.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • 1
    One wrinkle in this can come up if you can't know ahead of time which locks you'll need (for instance, halfway through `doStuff()` you find you need a new lock). In that case, one option is to try to acquire the lock via `tryLock()`. If that succeeds, great. If not, you unwind everything, undo all your work, and then retry it all with the locks you need. – yshavit Nov 06 '14 at 18:20
  • 1
    @yshavit Sure. There's a fair amount of literature on the problem with respect to Software Transactional Memory. – Tom Hawtin - tackline Nov 06 '14 at 18:30