How to lock multiple critical sections in code?

78 views Asked by At

I'm learning about multi-threading in C# and found out that the Mutex class, can help me to synchronize threads working. So, I want to use the ThreadPool (limited to 10 threads) and this thread's should wait sometimes because there are multiple critical sections in my code. I have some calls to a few Web services and to a DB and I want to handle that only one thread can access to this external resources at time.

e.g.:

Mutex mutex = new Mutex(true);

//method for DB Access
private void callDB()
{
    mutex.WaitOne();
    //Do DB Call
    mutex.ReleaseMutex();
}

//method for WS1
private void callWS1()
{
    mutex.WaitOne();
    //Do WS Call
    mutex.ReleaseMutex();
}

There is only one mutex in my class. For example, if Thread 1 does the callDB and release the mutex for the next thread, what would happen if Thread 1 reach the callWS1 method and lock the mutex there?

Is the mutex blocking for the whole class (and for the other threads) or only for the specified critical section?

Do I have to create multiple mutex instances if I want to use mutex at different locations in code? Is there probably an other, smarter solution for this situation?

1

There are 1 answers

1
teapot418 On BEST ANSWER

One Mutex instance can only be held in one place (/thread) at any given time. Everyone else wanting to acquire that mutex has to wait until it's released.

You can have one giant mutex used by everyone, it will definitely serialize access, but there will be a lot of waiting. So one instance for everybody is safe, but bad for performance.

Ideally you would have one mutex per resource (variable, data structure, ...) you want to protect. So e.g. there would be one for database access that would be used in all code locations that do stuff with the database.

Although your examples are not ideal, both web services and databases are usually prepared to deal with multiple concurrent accesses, so there should be no need for this kind of locking for them.