glib: Multi-thread safety with GArray



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?

Thanks,

Lionel




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