Possible Duplicate:
Malloc thread-safe?可能重复:Malloc线程安全吗?
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?
我听说glibc malloc()不是线程安全的,因为同时调用malloc()的进程的几个线程将导致未定义的行为。我的问题是,如果一个线程调用free(),另一个线程正在调用malloc(),这会导致未定义的行为吗?
3 个解决方案
#1
If you link with -pthreads, malloc() will be threadsafe in glibc.
如果你用-pthreads链接,malloc()将是glibc中的线程安全。
Without that, the linker doesn't link in a threadsafe malloc, which will lead to undefined behavior.
没有它,链接器不会在线程安全malloc中链接,这将导致未定义的行为。
#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().
这取决于你的glibc实现。系统上的一个简单的“man malloc”可能会告诉你。通常,如果您告诉编译器您将使用线程,那么它将链接到c运行时库的线程安全版本,包括线程安全的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.
它实际上取决于你正在使用的内存分配器,但是,我认为默认情况下,malloc和free是不可重入的,因为它们维护静态列表中的内存块列表。
This could lead to complications if you're malloc'ing and freeing simultaneously.
如果你同时进行malloc'ing和释放,这可能会导致并发症。
I know that ptmalloc
, however, is threadsafe, so you could use that instead.
我知道ptmalloc是线程安全的,所以你可以使用它。
These links were also useful:
这些链接也很有用:
#1
If you link with -pthreads, malloc() will be threadsafe in glibc.
如果你用-pthreads链接,malloc()将是glibc中的线程安全。
Without that, the linker doesn't link in a threadsafe malloc, which will lead to undefined behavior.
没有它,链接器不会在线程安全malloc中链接,这将导致未定义的行为。
#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().
这取决于你的glibc实现。系统上的一个简单的“man malloc”可能会告诉你。通常,如果您告诉编译器您将使用线程,那么它将链接到c运行时库的线程安全版本,包括线程安全的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.
它实际上取决于你正在使用的内存分配器,但是,我认为默认情况下,malloc和free是不可重入的,因为它们维护静态列表中的内存块列表。
This could lead to complications if you're malloc'ing and freeing simultaneously.
如果你同时进行malloc'ing和释放,这可能会导致并发症。
I know that ptmalloc
, however, is threadsafe, so you could use that instead.
我知道ptmalloc是线程安全的,所以你可以使用它。
These links were also useful:
这些链接也很有用: