Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Multiple C++ Threads execute on a class method

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.

like image 963
Paul Baumer Avatar asked Dec 05 '25 06:12

Paul Baumer


1 Answers

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

like image 115
Adam Rosenfield Avatar answered Dec 07 '25 20:12

Adam Rosenfield