|
-
June 17th, 2010, 04:14 AM
#1
[RESOLVED] Access Global Variable
I have been asked this question in my recent interview...
"How can we make sure that only one thread access global variable?"
What's the appropriate answer.
Thanks all
-
June 17th, 2010, 07:28 AM
#2
Re: Access Global Variable
Did you have any answer at all? I would think most programmers know about critical sections and mutexes.
-
June 17th, 2010, 08:10 AM
#3
Re: Access Global Variable
Yeah i know about critical sections and mutexes, but that's not the question, He wants that how can Only and only one thread can access that variable... BTW i got my answer in "Thread Local Storage", Which i didn't know at that time
-
June 17th, 2010, 02:29 PM
#4
Re: Access Global Variable
IMO, using TLS and global variables is fragile.
I would prefer to create a global singleton class that contains thread safe variable accessors. This hides the thread synchronization details from callers of the class.
For example:
Code:
// In thread 1
int value = Manager.GetInstance( ).GetValue( );
// In thread 2
Manager.GetInstance( ).SetValue( 10 );
This ends up pretty clean because the callers need not concern themselves with any thread synchronization details.
Using the globle variable approach you force callers of the global variable to provide the thread synchronization, which usually is an approach that results in more bugs.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|