Re: Are g_try_malloc() and g_free() thread-safe?

> Can anyone say with certainty whether g_try_malloc() and g_free() are
> thread-safe?  I've spent considerable time searching mailing lists and
> googling and have found only sketchy opinions at best.

glib itself is thread safe, while the user-side is not. g_malloc and
g_free is thread safe. a GList for instance is not.

> Historically, I have been wrapping all of my allocations and releases in
> a global mutex, but this seems far from optimal.  I assume that these
> functions are implementations of malloc() and free(), but again it seems
> there is no definitive answer to my question.

malloc and free are not thread-safe unless you define _REENTRANT or such
alike. g_malloc/g_free do not wrap around malloc/free. glib has its own
internal memory management as far as I know.

> If these functions lock the heap during memory allocations and releases
> then my wrappers are pointless.  However, I have noticed that when I
> don't use the global mutex wrapper, g_try_malloc will often return an
> invalid address (not NULL as documented) or my data will be corrupt when
> it is access across threads.

That should not happen.

> Basically, my application has several threads which push and pop
> "messages" to/from a linked-list.  The data (message) for each node is
> allocated from the heap when it is "pushed" and freed by the processing
> loop when it is "popped".  The result is that there can be several
> hundred messages which are allocated and freed within a very microscopic
> time frame.  Since my linked-list is independently locked
> (g_static_mutex_lock), I am confident the problem lies outside the list
> mechanism.

In that case. there is a glib but out there. Atleast that is my toughts.

Stian Skjelstad

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]