Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is malloc thread-safe?

Is the malloc() function re-entrant?

like image 493
Alphaneo Avatar asked May 13 '09 02:05

Alphaneo


People also ask

Is malloc multithread safe?

None of the common versions of malloc allow you to re-enter it (e.g. from a signal handler). Note that a reentrant routine may not use locks, and almost all malloc versions in existence do use locks (which makes them thread-safe), or global/static variables (which makes them thread-unsafe and non-reentrant).

Is malloc thread-safe on Windows?

Provided you're linking with thread-safe libraries and using the correct flags, yes, malloc should be thread-safe.

Is free () thread-safe?

By default, new/delete are often not thread safe in a FreeRTOS app because the basic malloc and free are not thread safe. Some embedded libraries have hooks that can be defined to make these functions thread safe.

Is malloc shared between threads?

malloc() and free() are not thread-safe functions. You need to protect the calls to those functions with a mutex. You need to protect all shared variables with a mutex as well.


1 Answers

Question: "is malloc reentrant"?
Answer: no, it is not. Here is one definition of what makes a routine reentrant.

None of the common versions of malloc allow you to re-enter it (e.g. from a signal handler). Note that a reentrant routine may not use locks, and almost all malloc versions in existence do use locks (which makes them thread-safe), or global/static variables (which makes them thread-unsafe and non-reentrant).

All the answers so far answer "is malloc thread-safe?", which is an entirely different question. To that question the answer is it depends on your runtime library, and possibly on the compiler flags you use. On any modern UNIX, you'll get a thread-safe malloc by default. On Windows, use /MT, /MTd, /MD or /MDd flags to get thread-safe runtime library.

like image 95
Employed Russian Avatar answered Sep 19 '22 19:09

Employed Russian