Does a thread have its own memory space?

Does a thread have its own memory space?

Yes. Each thread has its own stack, but all the memory associated with the process is in the same virtual address space. If a function in one thread had a pointer to a stack-allocated variable in another thread, that function could read from/write to that variable.

Why do threads share heap?

Heap – Since global variable is stored in the heap, heap is shared among threads. Stack – Since each thread can have its own execution sequence/code, it must have its own stack on which it might push/pop its program counter contents (when say function calls and returns happen).

Do threads share data segment?

Threads share the code and data segments and the heap, but they don’t share the stack.

Can a thread share memory with another thread?

Threads can share memory on a heap if they both use the same heap. By default most languages/frameworks have a single default heap that code can use to allocate memory from the heap.

Why do threads not share the heap space?

As for why stacks are not shared, that’s because an execution thread has to have its own stack to be able to manage its call tree (it contains information about what to do when you leave a function, for instance!). The problem is that having local heaps adds significant complexity for very little value.

Can a resource be shared among all threads?

Resource sharing: Resources like code, data, and files can be shared among all threads within a process. Note: stack and registers can’t be shared among the threads. Each thread has its own stack and registers. 5.

Is it possible to hold pointer to memory in another thread?

Threads have independent call stacks, however the memory in other thread stacks is still accessible and in theory you could hold a pointer to memory in some other thread’s local stack frame (though you probably should find a better place to put that memory!). From Wikipedia (I think that would make a really good answer for the interviewer :P)