This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

basic_string::release and thread safety: what about basic_string::grab?


The v2 version of basic_string::Rep::release has been changed to be
thread-safe on the x86 and sparc platforms by using atomic instructions
to decrement the reference count.  However, basic_string::Rep::grab, which
increments the reference count, is not protected.

What prevents the following sequence from occuring, where two threads
manipulate strings that share a reference:

thread 1 calls grab, which does (if selfish is not set)
	++ref; return data();

On most processors this turns into assembly that does
	read ref -> register,
	add 1 to register,
	store register -> ref

It could happen that thread 2 calls release, after thread 1's grab call
has read ref but before it has written it.

It seems that we can eliminate the case where ref is 1, meaning that there
is only one reference (this means that the two threads are using the same
basic_string, not just the same basic_string::Rep).  Such cases are
fraught with race conditions even if we don't use reference counting.  So
let's say that ref is initially 2 (the threads have different basic_string
objects but share the same Rep).  Thread 1 (in grab) reads 2.  Thread 2
(in release) then reads 2 and atomically stores back 1.  Finally thread 1
stores 3.  The reference count is now too high, meaning that we will
eventually have a memory leak.

So, should basic_string::Rep::grab also use an atomic instruction to
increment grab?  Or is the low-probability memory leak OK?


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]