About Static Variable and Thread-Safe

This is a discussion on About Static Variable and Thread-Safe within the C++ Programming forums, part of the General Programming Boards category; I was asked to write a function with a static variable in it. for example: Code: void foo(){ static int ...

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    284

    About Static Variable and Thread-Safe

    I was asked to write a function with a static variable in it. for example:

    Code:
    void foo(){
    static int a=1;
    a++;
    }
    Obviously this is not thread safe. Then I was asked to solve this problem to make it thread safe.
    I was told that I can use a class to wrap it. Does anybody has an idea what that is?

    Do you have a better solution?
    Last edited by meili100; 06-06-2007 at 07:58 PM.

  2. #2
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    think about why it isn't thread safe? what can you do to fix that?
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

  3. #3
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    If you don't know what a class is, consider learning that before you tackle thread synchronization.....

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 01-19-2009, 06:42 PM
  2. How make static variable for across threads?
    By 6tr6tr in forum C++ Programming
    Replies: 10
    Last Post: 04-22-2008, 08:32 AM
  3. Replies: 6
    Last Post: 12-13-2007, 07:20 PM
  4. Thread Synchronization in Win32
    By passionate_guy in forum C Programming
    Replies: 0
    Last Post: 02-06-2006, 04:34 AM
  5. Replies: 2
    Last Post: 04-12-2004, 01:37 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21