Type of master / slave lock system?

I have no clue if the thing I want to do has a name or not. The "Master / Slave Lock System", unfortunately, is the best language I could come up with.

Now for the problem I have ...

Imagine you have the following class:

public class Foo
{
    public void Master()
    {

    }

    public void Slave1()
    {

    }

    public void Slave2()
    {

    }
}

I want the slave methods (Slave1, Slave2) to be executed in parallel in a multi-threaded script, but when the master (Master) method is called, the slaves method must be blocked from execution while it is running, additional all the current slave methods must end after the master method is entered .

Something like this (with comments):

public class Foo
{
    public void Master()
    {
        //block slaves from executing
        //wait for slaves to finish

        //do code...

        //unblock slaves
    }

    public void Slave1()
    {
        //if blocked by master wait, if not execute
        //if currently running when entering master method, let it finish
    }

    public void Slave2()
    {
        //if blocked by master wait, if not execute
        //if currently running when entering master method, let it finish
    }
}

I know that I can use a lock for all 3 methods, but Slave1 methods will block each other, and this is not what I want.

public class Foo
{
    private readonly object _syncLock = new object();

    public void Master()
    {
        lock (_syncLock) //blocks Slave1, Slave2
        {
            //run code...
        }
    }

    public void Slave1()
    {
        lock (_syncLock) //blocks Slave2, Master - dont want that
        {
            //run code...
        }
    }

    public void Slave2()
    {
        lock (_syncLock) //blocks Slave1, Master - dont want that
        {
            //run code...
        }
    }
}

, , - " , ", , .

+4
1

,

  • () Master() ( SlaveN )
  • () Slave ( SlaveN, Master)

, , ReaderWriterLockSlim:

public class Foo {
    private readonly ReaderWriterLockSlim _syncLock = new ReaderWriterLockSlim();

    public void Master() {
      // Exclusive (write) lock: only Master allowed to run
      _syncLock.EnterWriteLock();

      try {
        //run code...
      }
      finally {
        _syncLock.ExitWriteLock();
      }   
    }

    public void Slave1() {
      // Read lock: you can run Slave2 (with another Read lock), but not Master 
      _syncLock.EnterReadLock();

      try {
        //run code...
      }
      finally {
        _syncLock.ExitReadLock();
      }         
    }

    public void Slave2() {
      // Read lock: you can run Slave1 (with another Read lock), but not Master 
      _syncLock.EnterReadLock();

      try {
        //run code...
      }
      finally {
        _syncLock.ExitReadLock();
      }         
    }   
}
+2

Source: https://habr.com/ru/post/1666463/


All Articles