473,408 Members | 2,813 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

C#: When to use monitor, lock object, mutex and other syn. objects

Hi,
Can anyone clear me that, when should we use go for mutex, and in which situation should we opt for monitor, lock, semaphone and other objects, in a multithreaded application for synchronization ?

Thanks
Jul 21 '05 #1
4 20703
<"=?Utf-8?B?VmluYXkgQw==?=" <Vinay C@discussions.microsoft.com>>
wrote:
Can anyone clear me that, when should we use go for mutex, and in
which situation should we opt for monitor, lock, semaphone and other
objects, in a multithreaded application for synchronization ?


I would suggest using Monitor (via the lock statement for Enter/Exit)
almost always. Mutex is useful if you want an inter-process lock.
Semaphores are useful for "counted" resources. Auto/ManulResetEvent are
useful for signalling situations where either you want to signal before
waiting (where Monitor.Pulse/Wait don't work as well) or you want to be
able to wait for any or all of multiple events.

See http://www.pobox.com/~skeet/csharp/multithreading.html for more
threading information. I'm updating it and adding
Auto/ManualResetEvent, but I haven't put that in yet.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #2
In a nutshell:
- Monitor.Enter/Exit and Mutexes are commonly used for protecting objects
from being used by two threads at the same time. Every thread acquires the
mutex (resp. enters the monitor) before it uses the object, and no other
thread will be allowed to do the same until the mutex is released (resp. the
monitor is exited); The Monitor methods are faster and use less memory,
mutexes can be shared across processes
- the lock statement internally uses the Monitor.Enter/Exit methods
- Monitor.Pulse/Wait are used for sending events to other threads;
Monitor.Wait will wait until "Pulse" is called by another thread. They are
usually used to wake up some idling thread. (AutoResetEvent/ManualResetEvent
serve similar purposes)
- Semaphores are much like mutexes, however they permit more than one access
at a time (e.g. it you want at most 3 of your threads accessing a database
at a time)

I hope this short intro helps a little; Jon Skeet has an excellent article
on multithreading, you could use google to find it.

Niki

"Vinay C" <Vinay C@discussions.microsoft.com> wrote in
news:3C**********************************@microsof t.com...
Hi,
Can anyone clear me that, when should we use go for mutex, and in which situation should we opt for monitor, lock, semaphone and other objects, in a
multithreaded application for synchronization ?
Thanks

Jul 21 '05 #3
Thank you, your matter was very useful. but still I have some queries
1. When I should chose monitor and when should I go for mutex, whats difference between them regarding performance.)
2. Please see a part of the code below:
public static void Main()
{
Threadpool1 tpool = new Threadpool1();
int total=2;
int completed =0;

ThreadPool.QueueUserWorkItem(new WaitCallback(tpool.increment));
ThreadPool.QueueUserWorkItem(new WaitCallback(tpool.decrement));

Thread.Sleep(500);

}
here I have to give Sleep() in main explicitly so that the main should not terminate before the threads in threadpool. Can you suggest the use of some other thing or callbacks so that we can know when the threads in threadpool are terminated thus avoiding Sleep() in main .

Eagerly waiting for the kind replies. :-)

"Jon Skeet [C# MVP]" wrote:
<"=?Utf-8?B?VmluYXkgQw==?=" <Vinay C@discussions.microsoft.com>>
wrote:
Can anyone clear me that, when should we use go for mutex, and in
which situation should we opt for monitor, lock, semaphone and other
objects, in a multithreaded application for synchronization ?


I would suggest using Monitor (via the lock statement for Enter/Exit)
almost always. Mutex is useful if you want an inter-process lock.
Semaphores are useful for "counted" resources. Auto/ManulResetEvent are
useful for signalling situations where either you want to signal before
waiting (where Monitor.Pulse/Wait don't work as well) or you want to be
able to wait for any or all of multiple events.

See http://www.pobox.com/~skeet/csharp/multithreading.html for more
threading information. I'm updating it and adding
Auto/ManualResetEvent, but I haven't put that in yet.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Jul 21 '05 #4
<"=?Utf-8?B?VmluYXkgQw==?=" <Vinay C@discussions.microsoft.com>>
wrote:
Thank you, your matter was very useful. but still I have some queries
1. When I should chose monitor and when should I go for mutex, whats
difference between them regarding performance.)
As I said before, only use Mutex for interprocess locking - it's much
less efficient than monitors.
2. Please see a part of the code below:
public static void Main()
{
Threadpool1 tpool = new Threadpool1();
int total=2;
int completed =0;

ThreadPool.QueueUserWorkItem(new WaitCallback(tpool.increment));
ThreadPool.QueueUserWorkItem(new WaitCallback(tpool.decrement));

Thread.Sleep(500);

} here I have to give Sleep() in main explicitly so that the main
should not terminate before the threads in threadpool. Can you
suggest the use of some other thing or callbacks so that we can know
when the threads in threadpool are terminated thus avoiding Sleep()
in main .


You should make your work items effectively release a semaphore, and
try to acquire the semaphore the same number of times in your Main
thread. Alternatively, give each of them an event or monitor to
set/pulse and wait until both have been set/pulsed.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Hal Vaughan | last post by:
If I have a class like this: public class Tester { ObjectType1 ot1; ObjectType2 ot2; ObjectType3 ot3; public void main(String args) { //Preliminary checking, resulting in bRun being
1
by: KN | last post by:
Hello, I'm new to this list, and I have an important question at the beginning. There is a matter that concerns me - it's the globales implementation. I've read nearly everything I found about...
1
by: tracy | last post by:
hi, when i run this sql,i got this error SQL> grant all on raw_ptptn_data to unitem_role; grant all on raw_ptptn_data to unitem_role * ERROR at line 1: ORA-04021: timeout occurred while waiting...
4
by: Vinay C | last post by:
Hi, Can anyone clear me that, when should we use go for mutex, and in which situation should we opt for monitor, lock, semaphone and other objects, in a multithreaded application for synchronization...
6
by: Clark Sann | last post by:
Can someone help me understand what object should be used as the lock object? I've seen some programs that use Monitor.Enter(Me). Then, in those same programs, they sometimes use another object. ...
0
by: adnanahmed714 | last post by:
Hi Experts! i made a application for plant monitoring.Can some one help me , to access(Run+ Monitor) VB application from other Computer on the Network. I just want to monitor the forms on the...
3
by: gautamga | last post by:
Hi anybody, I was getting error like below while compiling package SQL> @pkg_utility.sql CREATE OR REPLACE PACKAGE pkg_utility * ERROR at line 1: ORA-04021: timeout occurred while waiting to...
1
by: gautamga | last post by:
Hi anybody, I was getting error like below while compiling package SQL> @pkg_utility.sql CREATE OR REPLACE PACKAGE pkg_utility * ERROR at line 1: ORA-04021: timeout occurred while waiting to...
2
by: valentin tihomirov | last post by:
It is quite convenient to use the basic primitive: lock(object) { method(); } On the other hand, rwLock.AcquireReaderLock(-1); try { // unlock finally
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.