Mutex object

Should I create a new Mutex object per thread accessing a shared
resource or is it per shared resource being accessed. I understand that
I need to create a Mutex object and use the synchronize method to make
the associated block appear as an atomic operation but not sure how to
decide when and how many Mutex objects need to be created. Can someone
explain.

thanks.

You need one mutex by resource. The Mutex will control the access to
that object, giving exclusive permission for a thread to modify it.
If you have a list and a hash, for example, that will be shared by
three threads, you’ll need two mutexes: one for the list, and one for
the hash. While a thread modifies the list, others can modify the
hash, and so on. It’s a good practice to always synchronise multiple
mutexes in the same order, to prevent deadlocks.

2010/3/8 p0Eta [email protected]:

You need one mutex by resource. The Mutex will control the access to
that object, giving exclusive permission for a thread to modify it.
If you have a list and a hash, for example, that will be shared by
three threads, you’ll need two mutexes: one for the list, and one for
the hash.

This is only true if the Array and the Hash are supposed to be
manipulated independently. If they need to be changed in sync, you
need a single mutex.

While a thread modifies the list, others can modify the
hash, and so on. It’s a good practice to always synchronise multiple
mutexes in the same order, to prevent deadlocks.

… if you need to hold more than one lock, yes.

OP, you need one mutex or monitor per critical section. How many
objects you manipulate in that critical section is totally dependent
on the logic to execute. If you allocate mutexes per thread, you do
not have mutexes (“mutual exclusion”) - assuming each thread gets its
own mutex.

Kind regards

robert