-2

As I got to know that apart from data segment and code segment threads also share heap segment

What resources are shared between threads??

then if I create a variable dynamically using malloc() or calloc() inside the thread then does that variable would be accessible to all the other threads of the same process?

Nick
  • 1
  • 2
  • HI ! Welcome to Stack Overflow ! Please [take the tour](https://stackoverflow.com/tour) before going on with your question. I would suggest you rephrase it as it is very difficult to understand. – Xatyrian Jan 13 '18 at 12:13

1 Answers1

0

Theoretically, if you know the memory address. Yes, heap allocated variables should be accessible from any thread within the same process.

{malloc, calloc, realloc, free, posix_memalign} of glibc-2.2+ are thread safe

http://linux.derkeiler.com/Newsgroups/comp.os.linux.development.apps/2005-07/0323.html

Original post

Generally, malloc/new/free/delete on multi threaded systems are thread safe, so this should be no problem - and allocating in one thread , deallocating in another is a quite common thing to do.

As threads are an implementation feature, it certainly is implementation dependant though - e.g. some systems require you to link with a multi threaded runtime library.

And this

Besides also answered in: the link you posted

Threads differ from traditional multitasking operating system processes in that:

  • processes are typically independent, while threads exist as subsets of a process processes carry considerable state information, whereas
  • multiple threads within a process share state as well as memory and other resources processes have separate address spaces, whereas
  • threads share their address space processes interact only through system-provided inter-process communication mechanisms. Context
  • switching between threads in the same process is typically faster than context switching between processes.

So, yes it is.

AgentM
  • 338
  • 2
  • 15