0

I am using the following code

class foo
{
    private:
    int val;

public:

    void someMethod()
    {
        std::cout << val ;
    }

    foo()
    {
        val = 12;
        boost::thread t(&foo::someMethod,this);
    }
};

I am accessing this class as:

foo f;

Now from what I understand is that all the member variables of f are created on the stack. From this thread I understand that threads share the same heap of the program but each thread has its own stack space. I wanted to know how someMethod() running in its own thread have access to the class variable.

Community
  • 1
  • 1
MistyD
  • 16,373
  • 40
  • 138
  • 240
  • You're passing the object. The object contains the data. – chris Nov 25 '13 at 00:01
  • The thread accesses the data via the `this` pointer. This works because the thread is in the same virtual memory space as the process in which it is launched. – juanchopanza Nov 25 '13 at 00:05
  • A pointer to something on another thread's stack is in the end just another pointer... – asveikau Nov 25 '13 at 00:05
  • Aaannd another example where excessive obsessing with "stack" and "heap" distracts from the real issue and only serves to confuse. – Kerrek SB Nov 25 '13 at 00:06

1 Answers1

2

You are passing the this pointer to the thread. A pointer, well, can point to an arbitrary location, in that case it will point to the stack. This works theoretically but is very unsafe.

Consider the following code:

if (...) 
{
    foo f;
}

What will happen?

  1. The scope of the if-block is entered
  2. The foo instance is initialized on the stack
  3. The thread starts with a foo* pointing to the stack
  4. The scope of the if-block is left
  5. Thus f becomes destructed/deleted and the space where it was contained (the stack) possible deallocated.

Now while the thread might run flawlessly for some micro seconds, after that little little little time you will get big big big trouble because the this pointer the thread works with is now invalid. Very bad!

Sebastian Hoffmann
  • 11,127
  • 7
  • 49
  • 77