473,890 Members | 3,926 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about boxing and using Monitor::Enter / Monitor::Exit.

If I have a value type such as int that I want to protect in a
multi-threaded situation, Is it safe to use Monitor::Enter( __box(value))?
I am thinking that a different object pointer is generated each time and
thus the protection is not insured. Is this true or not?

Example:

public _gc class MyClass
{
int Value;

void IncValue()
{
Monitor::Enter( __box(Value));
Value++;
Monitor::Exit(_ _box(Value));
}
};
--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.

EmailID = varnk
Domain = Diebold.com
-----------------------------------
Nov 17 '05 #1
5 2086
Ken Varn wrote:
If I have a value type such as int that I want to protect in a
multi-threaded situation, Is it safe to use Monitor::Enter( __box(value))?
I am thinking that a different object pointer is generated each time and
thus the protection is not insured. Is this true or not?

Example:

public _gc class MyClass
{
int Value;

void IncValue()
{
Monitor::Enter( __box(Value));
Value++;
Monitor::Exit(_ _box(Value));
}
};


Your hunch is correct. That's not going to work for the reason you say. You
can synchronize on MyClass, or if that feels too coarse, you can create a
new System::Object and dedicate it to protecting Value. The latter is
probably the better approach.

--
Doug Harrison
Microsoft MVP - Visual C++
Nov 17 '05 #2
Yikes! Don't you guys make voting machines?

Your surmise is correct, what you've posted won't work.

You have two main approaches.

1) System.Threadin g.Interlocked.I ncrement is an atomic (and therefore
somewhat thread-safe) operation.

2) Have a private locking object; this will allow more complex atomic
operations.

int Votes;
Object Locking; // = new Object(); in the constructor

void PlaceVote()
{
__try // In case you're going to do something that might throw.
{
Monitor::Enter( Locking );
// NB Don't use Enter( this ) or Enter( typeof(...) )

++Votes;
}
__finally
{
Monitor::Exit( Locking );
}
}

C# has a shortcut for this pattern, namely the lock statement.

Hope that helps,
Stu
"Ken Varn" <nospam> wrote in message
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..
If I have a value type such as int that I want to protect in a
multi-threaded situation, Is it safe to use Monitor::Enter( __box(value))?
I am thinking that a different object pointer is generated each time and
thus the protection is not insured. Is this true or not?

Example:

public _gc class MyClass
{
int Value;

void IncValue()
{
Monitor::Enter( __box(Value));
Value++;
Monitor::Exit(_ _box(Value));
}
};
--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.

EmailID = varnk
Domain = Diebold.com
-----------------------------------

Nov 17 '05 #3
Thanks for the info.

BTW. I do not work on voting machines. That is a completely different
division.

--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.

EmailID = varnk
Domain = Diebold.com
-----------------------------------
"Stu Smith" <st*****@nosp am-digita.com> wrote in message
news:eF******** ******@TK2MSFTN GP12.phx.gbl...
Yikes! Don't you guys make voting machines?

Your surmise is correct, what you've posted won't work.

You have two main approaches.

1) System.Threadin g.Interlocked.I ncrement is an atomic (and therefore
somewhat thread-safe) operation.

2) Have a private locking object; this will allow more complex atomic
operations.

int Votes;
Object Locking; // = new Object(); in the constructor

void PlaceVote()
{
__try // In case you're going to do something that might throw.
{
Monitor::Enter( Locking );
// NB Don't use Enter( this ) or Enter( typeof(...) )

++Votes;
}
__finally
{
Monitor::Exit( Locking );
}
}

C# has a shortcut for this pattern, namely the lock statement.

Hope that helps,
Stu
"Ken Varn" <nospam> wrote in message
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..
If I have a value type such as int that I want to protect in a
multi-threaded situation, Is it safe to use Monitor::Enter( __box(value))? I am thinking that a different object pointer is generated each time and
thus the protection is not insured. Is this true or not?

Example:

public _gc class MyClass
{
int Value;

void IncValue()
{
Monitor::Enter( __box(Value));
Value++;
Monitor::Exit(_ _box(Value));
}
};
--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.

EmailID = varnk
Domain = Diebold.com
-----------------------------------


Nov 17 '05 #4
Thanks for the info. I am curious about one thing though. Is there any
difference in using an object for synchronization using Monitor vs. using a
Mutex object?

--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.

EmailID = varnk
Domain = Diebold.com
-----------------------------------
"Doug Harrison [MVP]" <ds*@mvps.org > wrote in message
news:i7******** *************** *********@4ax.c om...
Ken Varn wrote:
If I have a value type such as int that I want to protect in a
multi-threaded situation, Is it safe to use Monitor::Enter( __box(value))?I am thinking that a different object pointer is generated each time and
thus the protection is not insured. Is this true or not?

Example:

public _gc class MyClass
{
int Value;

void IncValue()
{
Monitor::Enter( __box(Value));
Value++;
Monitor::Exit(_ _box(Value));
}
};
Your hunch is correct. That's not going to work for the reason you say.

You can synchronize on MyClass, or if that feels too coarse, you can create a
new System::Object and dedicate it to protecting Value. The latter is
probably the better approach.

--
Doug Harrison
Microsoft MVP - Visual C++

Nov 17 '05 #5
Ken Varn wrote:
Thanks for the info. I am curious about one thing though. Is there any
difference in using an object for synchronization using Monitor vs. using a
Mutex object?


For basic synchronization in a single process, no. However, with Mutex you
can create a named mutex to use across processes, and you can wait on
multiple Mutexes and other WaitHandle-derived objects in a single
WaitHandle::Wai tAny or WaitAll call. On the other hand, Monitor supports
condition variable programming with its Pulse members. For more on all this,
see:

Threading Objects and Features
http://msdn.microsoft.com/library/de...tsFeatures.asp

--
Doug Harrison
Microsoft MVP - Visual C++
Nov 17 '05 #6

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

Similar topics

5
3858
by: bughunter | last post by:
Hi, Consider this code: ---- Monitor.Pulse(oLock); Monitor.Exit(oLock); ---- If a thread was waiting on oLock then will the current thread
2
13222
by: Shawn B. | last post by:
Greetings, What is the difference between lock(...) and Monitor.Enter(...) / Monitor.Exit(...) ? Thanks, Shawn
6
2151
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. Why? I would appreciate it if someone could help me understand the ramifications of picking an object in this command. Thank you so much for your help. Clark
3
2017
by: Rudi | last post by:
Hi I've got a CollectData() method which is called by Timer periodically. CollectData calls Add(input) - the problem is the code after Add(input) in CollectData() is never executed. It's as if the monitor is never closed. CollectData() never executes further then Add(input), except I remove the monitors. It's an Windows CE 5.0 application. What is my problem? Hope someone can help.
1
5189
by: soriold | last post by:
Hey there: I am done writing a rather large program for school and the only thing that is still driving me nuts is how to exit the program based on the fact that the return/carriage key was pressed. All input is stored as characters in an array... something like this: char input1; cout << "Enter number 1 (0-99999999):"; cin >> input1; At this point I need to be able to determine if the user simply hits the ENTER KEY/CARRIAGE RETURN....
4
3496
by: MyProblem | last post by:
Hi, I just tried to convert my current project to the new beta 2 of the .net framework and I encountered some problems with my thread synchronization - that formerly worked well. System.Threading.SynchronizationLockException: Object synchronization method was called from an unsynchronized block of code. Code is below Monitor.Enter (collectionvar );
13
2687
by: AliRezaGoogle | last post by:
Dear Members, I have a problem in the concepts of Monit.Enter and Monitor.Exit (Before everything I should say that I know how to solve this problem by using Monitor.Wait and I do not need a solution. But this question sticks to my head as a conceptual problem) Suppose there are two threads T1, T2 running concurrently:
0
9979
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9823
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10924
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10463
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
8017
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7170
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5854
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6049
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4681
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.