Click to See Complete Forum and Search --> : [RESOLVED] Access Global Variable


itsmeash
June 17th, 2010, 04:14 AM
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

hoxsiew
June 17th, 2010, 07:28 AM
Did you have any answer at all? I would think most programmers know about critical sections and mutexes.

itsmeash
June 17th, 2010, 08:10 AM
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 :)

Arjay
June 17th, 2010, 02:29 PM
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:

// 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.