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

    what are the possible outputs

    Hi,

    Suppuse I have the following function

    static int staticIntX = 2;

    int inc()
    {
    staticIntX++;
    return staticIntX;
    }

    What are the possible outputs for this function if 2 different threads are calling it?

    I understand that there are 3 possible answers:
    2,2
    2,3
    3,3

    the thing is that I do not undertand how the 2,2 result can happen.
    Can anyone explain?

    Thanks
    Avi

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

    Re: what are the possible outputs

    The output will depend on when the values are displayed - i.e. before or after incrementing. Also, since the static value is accessed by both threads without being protected you are going to get unpredictable results.

  3. #3
    Join Date
    Sep 2003
    Posts
    815

    Re: what are the possible outputs

    sure, but what are the possible outputs and why?

    Thanks
    Avi123

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

    Re: what are the possible outputs

    Quote Originally Posted by avi123
    sure, but what are the possible outputs and why?

    Thanks
    Avi123
    That's the issue. You will get unpredictable results because the static variable is accessed by both threads without synchronization (i.e. the variable access isn't threadsafe).

    The possible outputs will vary depending how it's coded, on the number of processors (or cores) and how the planets are aligned with the universe. I don't mean to sound flip, but this is the exact reason that synchronization is required when accessing a shared resource from multiple threads.

    If you provide synchronization in the form of a critical section or mutex, the possible outputs will be deterministic. If you don't synchronize, the output will be random (although may not appear random when tested on a single machine).

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