Mutex object

A

ash 34

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

p0Eta

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

Robert Klemme

2010/3/8 p0Eta said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,778
Messages
2,569,605
Members
45,238
Latest member
Top CryptoPodcasts

Latest Threads

Top