Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performing malloc in threads

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

like image 482
Lior Avatar asked Jan 07 '23 17:01

Lior


2 Answers

  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.
like image 93
fuz Avatar answered Jan 11 '23 17:01

fuz


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.

like image 27
cadaniluk Avatar answered Jan 11 '23 19:01

cadaniluk