Unless your implementation of class C's member functions uses self modifying code (unlikely), then accessing the program memory itself is not going to be a problem. Your problem is going to be access of shared mutable data and resources.
If I understand the question correctly you are saying that you would be creating a new instance of a class 'C' and exclusively calling come member function of class C from another thread.
e.g. psuedocode:
void thread1() {
auto_ptr<C> pc(new C());
while (1) {
pc->f();
}
}
void thread2() {
auto_ptr<C> pc(new C());
while (1) {
pc->f();
}
}
Since the code in function C::f() does not change it is safe to execute it concurrently.
However if the code in C::f() accesses any shared data then it is not safe unless you put in thread synchronization.
If, for example C::f() looked like this and C has a member variable 'int i_
' then this is safe provided no other threads change the value:
void C::f() {
++i_;
}
That is only safe if no other threads read or modify that instance of C's 'i_' member. In some cases it might be safe if only other threads read i_
but that is only if you can guarantee that writes to i_
are atomic. There are further caveats there to do with instruction ordering and what you might expect elsewhere in a program so any reliance on stuff like that needs extreme care. In this contrived example, no other threads are going to know about the instance of 'C' so it will be fine.
If C::f() looked like this:
void C::f() {
static int i = 0;
std::cout << i++ << std::endl;
}
Then it is definitely NOT safe. The static int is shared data - all calls to C::f have access to the same data regardless of what instance it is. There are data races with the static initializer for 'i
' (setting it to zero for the first time for which the compiler will insert some bookkeeping data). Additionally the increment of 'i
' is likely to not be an atomic operation -- so it is not safe.
The use of the global variable std::cout
here is also not thread safe. Even if the output stream implements a mutex internally, you are doing two separate operations here and you could get races. If there is no thread synchronization internally on the output stream then you are likely to have all manner of undefined behaviour.