Search code examples
performancemultithreadinglanguage-agnosticsynchronizationd

Efficient Independent Synchronized Blocks?


I have a scenario where, at certain points in my program, a thread needs to update several shared data structures. Each data structure can be safely updated in parallel with any other data structure, but each data structure can only be updated by one thread at a time. The simple, naive way I've expressed this in my code is:

synchronized updateStructure1();
synchronized updateStructure2();
// ...

This seems inefficient because if multiple threads are trying to update structure 1, but no thread is trying to update structure 2, they'll all block waiting for the lock that protects structure 1, while the lock for structure 2 sits untaken.

Is there a "standard" way of remedying this? In other words, is there a standard threading primitive that tries to update all structures in a round-robin fashion, blocks only if all locks are taken, and returns when all structures are updated?

This is a somewhat language agnostic question, but in case it helps, the language I'm using is D.


Solution

  • 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.