CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Mar 2009
    Posts
    102

    [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

  2. #2
    Join Date
    Feb 2005
    Posts
    2,160

    Re: Access Global Variable

    Did you have any answer at all? I would think most programmers know about critical sections and mutexes.

  3. #3
    Join Date
    Mar 2009
    Posts
    102

    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

  4. #4
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    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
  •  





Click Here to Expand Forum to Full Width

Featured