Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread synchronization with multiple methods

I have a static class with multiple static methods.

private static Session _session = new Session();

public static void Method1() {
    if(_session != null)
        _session.Action();
}
public static void Method2() {
    if(_session != null)
        _session.Action();
}
public static void Method3() {
    if(_session != null)
        _session.Action();
}
public static void Method4(string path) {
    _session.Disconnect();
    _session.Connect(new Config(path));
}

Method1, Method2, Method3 are fully thread safe, they can be safely called simultaneously from any number of threads. In fact, for performance reasons, I need to allow multiple threads to call Method1,2,3 concurrently.

The problem is, it is possible for Method1,2,3 to throw an exception when Method4() is being called. How do I allow multiple threads to call Method1,2,3 while also blocking them when Method4() is being called?

like image 689
Pierre-Luc Avatar asked Sep 16 '26 15:09

Pierre-Luc


1 Answers

As SLaks has pointed out, a ReadWriterLock was a great solution.

Here is what I ended up implementing:

private static ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
private static Session _session = new Session();

public static void Method1() {
    _lock.EnterReadLock();
    try {
        if(_session != null)
            _session.Action();
    }
    finally
    {
        _lock.ExitReadLock();
    }
}
public static void Method2() {
    _lock.EnterReadLock();
    try {
        if(_session != null)
            _session.Action();
    }
    finally
    {
        _lock.ExitReadLock();
    }
}
public static void Method3() {
    _lock.EnterReadLock();
    try {
        if(_session != null)
            _session.Action();
    }
    finally
    {
        _lock.ExitReadLock();
    }
}
public static void Method4(string path) {
    _lock.EnterWriteLock();
    try {
        if(_session != null)
            _session.Action();
    }
    finally
    {
        _lock.ExitWriteLock();
    }
}

Great performance, no threading issues!

like image 87
Pierre-Luc Avatar answered Sep 18 '26 05:09

Pierre-Luc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!