Paul Baumer
Paul Baumer

Reputation: 321

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.

Upvotes: 2

Views: 2939

Answers (4)

Nicola Bonelli
Nicola Bonelli

Reputation: 8287

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

Upvotes: 4

Alaric
Alaric

Reputation: 839

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).

Upvotes: 0

jmatthias
jmatthias

Reputation: 7605

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.

Upvotes: 0

Adam Rosenfield
Adam Rosenfield

Reputation: 400364

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

Upvotes: 15

Related Questions