-
September 20th, 2007, 06:31 AM
#1
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
-
September 20th, 2007, 02:19 PM
#2
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.
-
September 24th, 2007, 12:56 PM
#3
Re: what are the possible outputs
sure, but what are the possible outputs and why?
Thanks
Avi123
-
September 24th, 2007, 01:11 PM
#4
Re: what are the possible outputs
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|