Search code examples
c++windows-mobilememory-managementdynamic-memory-allocation

Is it safe to pass (synchronously) stack-allocated memory to other thread?


Recently I heard that memory in the stack is not shared with other thread and memory in the heap is shared with other threads.

I normally do:

HWND otherThreadHwnd;
DWORD commandId;
// initialize commandId and otherThreadHwnd

struct MyData {
  int data1_;
  long data2_;
  void* chunk_;
};

int abc() {
  MyData myData;
  // initialize myData
  SendMessage(otherThreadHwnd,commandId,&myData);
  // read myData
}

Is it alright to do this?


Solution

  • I think 2 different issues are being confused by whoever you "heard that memory in the stack is not shared with other thread":

    1. object lifetime - the data on the stack is only valid as long the thread doesn't leave the scope of the variable's name. In the example you giove, you're handling this by making the call to the other thread synchronously.

    2. memory address visibility - the addresses pspace for a process is shared among the various threads in that process. So variables addressable by one thread are addressable by other threads in that process. If you are passing the address to a thread in a different process, the situation is quite different and you'd need to use some other mechanism (which might be to ensure that the memory block is mapped into both processes - but that I don't think that can normally be done with stack memory).