// JP opened flex table

Click to See Complete Forum and Search --> : what are the possible outputs


avi123
September 20th, 2007, 07:31 AM
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

Arjay
September 20th, 2007, 03:19 PM
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.

avi123
September 24th, 2007, 01:56 PM
sure, but what are the possible outputs and why?

Thanks
Avi123

Arjay
September 24th, 2007, 02:11 PM
sure, but what are the possible outputs and why?

Thanks
Avi123That'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).

//JP added flex table