Hi Atul,
Did you verify that a race occurs?
I that should not be the case. QBasicAtomic::ref() and QBasicAtomic::deref() are atomic operations.
if (!x->ref.deref())
delete x;
The implementation of deref() is:
inline bool deref()
{ return q_atomic_decrement(&atomic) != 0; }
The first thread would do an atomic decrement from 1 to 0 and deref() will return false, so x will be deleted.
The second thread would do an atomic decrement from 0 to -1 and refer will return true, so x will NOT be deleted a second time.
Let me know if I’m wrong!
Creating a class that is fully thread safe can be very tricky. I’m not sure whether Packet is thread safe now. I remember I had some concerns with some functions but can’t say anything specific right now. It’ll be great if you can take a look at Packet from the multi-threading perspective.
Regards,
Peter
atul wrote:Dear all
While doing the refactoring of this function, the race poped out …. ;-)
if (!x->ref.deref())
delete x;
Now what happens thread T1 has finish checking the above conditional and is then pre empted … T2 runs the the same conditional and deletes x. Thread T1 resumes and deletes x …
As we are using thread safe functions to swap ( if I am right ) the pointers, we should consider all races
Adding multi-threading at some later point in the code is very hard …
—- cheers atul
