Re: glib: Multi-thread safety with GArray



On 18/09/03 06:30, Lionel Ains wrote:


Hello,

I am currently designing a sparse array toolkit, and to do that I'm re-using GLIB's GArrays. Having gone inside the code that handles GArrays (glib/garray.c), I could see the mechanisms for multi-thread safe use, but I'd like to understand the following: Mutexes are used for array_mem_chunk, so that allocation/deallocation of memory space is multi thread-safe. Isn't there also the need to protect modifications to a GArray from multi-thread issues?

For example, if two threads call g_array_append_vals() on the same GArray, at about the same time, why isn't there a lock condition in while manipulating the GArray? With the current design, isn't it possible that the memcpy of the new values of one thread is immediately followed by the memcpy of the new values of another thread, without having updated the length of the array?

Say that elements are bytes, we could have the following scenario:
* Initial content for a GArray:
GArray->data: 00 01 02
GArray->len = 3

* Thread 1 calls g_array_append_vals with new values being 03 04 05
(g_array_append_vals' memcpy call is performed for thread 1):
GArray->data: 00 01 02 03 04 05
GArray->len = 3

* Thread 2 calls g_array_append_vals with new values being 06 07
(g_array_append_vals' memcpy call is performed for thread 2):
GArray->data: 00 01 02 06 07 05
GArray->len = 3

(g_array_append_vals' array->len += len performed for thread 1):
GArray->data: 00 01 02 06 07 05
GArray->len = 6

(g_array_append_vals' array->len += len performed for thread 2):
GArray->data: 00 01 02 06 07 05
GArray->len = 8

We would end up having lost part of the new elements.
Can this happen with the current implementation of GArrays?
Is it up to the code that uses Garrays to handle the mutexes?

As with most data structures in glib, glib protects its internal structures from access by multiple threads (the mem chunks, etc), but not the user's data structures (in this case, the GArray).

If you want mutex protection for the array, you will have to provide it yourself in the application (which is much more likely to know where locking is really needed for the array).

James.

--
Email: james daa com au
WWW:   http://www.daa.com.au/~james/






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