473,699 Members | 2,702 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 2073
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
3847
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
13196
by: Shawn B. | last post by:
Greetings, What is the difference between lock(...) and Monitor.Enter(...) / Monitor.Exit(...) ? Thanks, Shawn
6
2141
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
2006
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
5179
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
3482
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
2672
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
8685
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
8613
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,...
0
9172
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
7745
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6532
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
5869
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
4374
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...
2
2344
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.