4

Stack for different thread is different.but what about Heap. If Heap is different for different threads, then how they share objects?

2 Answers 2

3

The standard implementation for operating system threads is that they share the same memory (i.e. heap), code, data, resource handles etc. Code using this kind of threading can share objects (although you should then be asking "How do they share objects safely?"). However, some languages (e.g. Erlang) offer their own version of threads which do not have access to shared memory. In such cases, there is no shared state and therefore no shared objects; these constructs communicate by some form of message passing.

2
  • I find the concept of threads that don't share memory confusing. Is that just saying they are different processes, not different threads?
    – user53141
    Commented Nov 20, 2013 at 19:59
  • No, I am referring to language/compiler constructs, rather than OS threads. The language can impose any restrictions it likes on such constructs, assuming the compiler can enforce that reliably, while still using them in a threaded way. Take a look at Erlang actors; lightweight threads with no shared state, which can be run remotely at little extra effort.
    – itsbruce
    Commented Nov 20, 2013 at 21:43
1

AFAICR, for a new user-space thread, the stack space is allocated in virtual memory by the operating system using the kernel-side of ZwAllocateVirtualMemory() routine. The stack pointer for the thread is set to the top of this block and the thread procedure is started (among some other setup, omitted here).

When the thread needs to dynamically allocate on the heap, it could use 'new', 'malloc()' or GlobalAlloc() - they all eventually go through the Native API 'RtlAllocateHeap()' which will allocate from a process heap. As there will be multiple threads doing this, it has to be thread-safe (by default, there is an option opt-out flag).

Once memory is allocated on the heap, any thread is free to do whatever it wants with it - there are not locks enforced by the operating system. It is up to the language/runtime to serialise access to the object if that is desired. Some languages have this built-in (e.g. 'synchronised'), for others it is all manual.

2
  • For windows particularly, How Heap is allocated for different threads belong to same process?Is heap is different for different threads. please clear me.
    – sk patra
    Commented Nov 21, 2013 at 9:13
  • Edited. The default process heap is one for each process and every thread in that process shares it. Commented Nov 21, 2013 at 17:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.