How do two or more threads share memory on the heap that they have allocated?

A really short answer from a bird's view (1000 miles above):
Threads are execution paths of the same process, and the heap actually belongs to the process (and as a result shared by the threads). Each threads just needs its own stack to function as a separate unit of work.


My interpretation of your question: How can thread A get to know a pointer to the memory B is using? How can they exchange data?

Answer: They usually start with a common pointer to a common memory area. That allows them to exchange other data including pointers to other data with each other.

Example:

  1. Main thread allocates some shared memory and stores its location in p
  2. Main thread starts two worker threads, passing the pointer p to them
  3. The workers can now use p and work on the data pointed to by p

And in a real language (C#) it looks like this:

//start function ThreadProc and pass someData to it
new Thread(ThreadProc).Start(someData)

Threads usually do not access each others stack. Everything starts from one pointer passed to the thread procedure.


Creating a thread is an OS function. It works like this:

  1. The application calls the OS using the standard ABI/API
  2. The OS allocates stack memory and internal data structures
  3. The OS "forges" the first stack frame: It sets the instruction pointer to ThreadProc and "pushes" someData onto the stack. I say "forge" because this first stack frame does not arise naturally but is created by the OS artificially.
  4. The OS schedules the thread. ThreadProc does not know it has been setup on a fresh stack. All it knows is that someData is at the usual stack position where it would expect it.

And that is how someData arrives in ThreadProc. This is the way the first, initial data item is shared. Steps 1-3 are executed synchronously by the parent thread. 4 happens on the child thread.