473,324 Members | 2,356 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,324 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 20698
<"=?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: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.