4

I'm writing an application in c which uses POSIX pthreads. In each thread there is a function which does malloc. So my questions are:

1) Am I guaranteed that each thread allocates a different, non-overlapping block of memory?

2) Is there access to the allocated memory from the main thread (which created the other threads that allocate memory)?

I am using gcc compiler on Windows, but I would like to know the answer for both Windows and Linux.

Thanks

Lior
  • 2,019
  • 1
  • 15
  • 22
  • malloc thread safety http://stackoverflow.com/questions/855763/is-malloc-thread-safe. And yes malloc is a "global" allocation mechanism, so every chunk of memory allocated such is visible to the whole process. – Jean-Baptiste Yunès Jan 30 '16 at 11:10

2 Answers2

6
  1. POSIX guarantees that malloc() is thread-safe in that it can be used in multiple threads concurrently. Typically, malloc() employs internal locking for this purpose.
  2. POSIX guarantees that a process has a single flat address space. Multiple threads for one process share an MMU configuration and have access to the same address space. Objects allocated in one thread are also accessible from the others.
fuz
  • 88,405
  • 25
  • 200
  • 352
3

From man malloc:

   +---------------------+---------------+---------+
   | Interface           | Attribute     | Value   |
   +---------------------+---------------+---------+
   | malloc(), free(),   | Thread safety | MT-Safe |
   | calloc(), realloc() |               |         |
   +---------------------+---------------+---------+

malloc & friends is thread-safe, so I don't think there's more to say. Since they all conform to C99, this holds true for both Linux and Windows.

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
  • I am not familiar with the term "thread-safe". But I assume from your answer that it refers exactly to what I asked? – Lior Jan 30 '16 at 11:12
  • 1
    @Lior It means that two threads concurrently calling the same function won't create an undefined mess and will work as expected. So yes, it means basically the same. Also read [this](http://stackoverflow.com/questions/261683/what-is-meant-by-thread-safe-code). – cadaniluk Jan 30 '16 at 11:13