views:

1197

answers:

4

Hello,

let's say we have a c++ class like:

class MyClass
{
   void processArray( <an array of 255 integers> )
   {
     int i ;
     for (i=0;i<255;i++)
     {
        // do something with values in the array
     }
   }
}

and one instance of the class like:

MyClass myInstance ;

and 2 threads which call the processArray method of that instance (depending on how system executes threads, probably in a completely irregular order). There is no mutex lock used in that scope so both threads can enter.

My question is what happens to the i ? Does each thread scope has it's own "i" or would each entering thread modify i in the for loop, causing i to be changing weirdly all the time.

+15  A: 

i is allocated on the stack. Since each thread has its own separate stack, each thread gets its own copy of i.

Adam Rosenfield
technically it'll probably be in a register but the idea is there.
Greg Rogers
Well technically it is referred to as a stack variable (because of its scope). Registers are just an implementation detail that is not relevant.
Martin York
A: 

Since i is a local variable it is stored on the thread's own private stack. Hence, you do not need to protect i with a critical section.

jmatthias
A: 

As Adam said, i is a variable stored on the stack and the arguments are passed in so this is safe. When you have to be careful and apply mutexes or other synchronization mechanisms is if you were accessing shared member variables in the same instance of the class or global variables in the program (even scoped statics).

Alaric
+4  A: 

Be careful. In the example provided the method processArray seems to be reentrant (it's not clear what happens in // do something with values in the array). If so, no race occurs while two or more threads invoke it simultaneously and therefore it's safe to call it without any locking mechanism. To enforce this, you could mark both the instance and the method with the volatile qualifier, to let users know that no lock is required. It has been published an interesting article of Andrei Alexandrescu about volatile qualifier and how it can be used to write correct multithreaded classes. The article is published here: http://www.ddj.com/cpp/184403766

Nicola Bonelli