About thread safety in malloc and free [duplicate]

感情迁移 提交于 2019-12-08 10:40:37

问题


Possible Duplicate:
Malloc thread-safe?

I heard that glibc malloc() was not thread safe, since several threads of a process calling malloc() simultaneously will lead to undefined behaviour. And my question is if a thread calls free() will another thread is calling malloc(), will this lead to undefined behaviour as well?


回答1:


If you link with -pthreads, malloc() will be threadsafe in glibc.

Without that, the linker doesn't link in a threadsafe malloc, which will lead to undefined behavior.




回答2:


It depends upon your glibc implementation. A simple "man malloc" on your system might tell you. In general if you tell the compiler that you will be using threads then it will link in a thread safe version of the c runtime library including a thread-safe malloc().




回答3:


It really depends on the memory allocator you're using, however, I think by default, malloc and free are non-reentrant as they maintain the list of blocks of memory in a static list.

This could lead to complications if you're malloc'ing and freeing simultaneously.

I know that ptmalloc, however, is threadsafe, so you could use that instead.

These links were also useful:

  • http://www.ibm.com/developerworks/linux/library/l-reent.html
  • http://kernelstudy.net/2009/01/07/malloc-and-free-are-thread-safe/


来源:https://stackoverflow.com/questions/987444/about-thread-safety-in-malloc-and-free

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!