Is malloc thread-safe?

2019-01-01 15:13发布

Is the malloc() function re-entrant?

11条回答
一个人的天荒地老
2楼-- · 2019-01-01 15:44

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.

查看更多
十年一品温如言
4楼-- · 2019-01-01 15:47

Yes, under POSIX.1-2008 malloc is thread-safe.

2.9.1 Thread-Safety

All functions defined by this volume of POSIX.1-2008 shall be thread-safe, except that the following functions1 need not be thread-safe.

[ a list of functions that does not contain malloc ]

查看更多
零度萤火
5楼-- · 2019-01-01 15:47

malloc and free are not reentrant, because they use a static data structure which records what memory blocks are free. As a result, no library functions that allocate or free memory are reentrant.

查看更多
公子世无双
6楼-- · 2019-01-01 15:52

It depends on which implementation of the C runtime library you're using. If you're using MSVC for example then there's a compiler option which lets you specify which version of the library you want to build with (i.e. a run-time library that supports multi-threading by being tread-safe, or not).

查看更多
登录 后发表回答