Re:Is reference counting slower than GC?
by vardump on Tuesday May 24, 2016 @05:54AM
(#11760129)
But if you have both atomic primitives available, why would you ever do that?
Keyword is atomic. Fetch-and-add returns you the previous value atomically.
-------
Edit:
This (below) is obviously a buggy reference counting algorithm.
-------
In freeing (decrementing reference count) thread A, if it was 1 before (returned value) and A added -1, the object can be freed.
Because the operation is atomic, only one of two things can happen:
1) Another reference adding thread B increments it before A decreases it. So A doesn't see 1, thus won't free the object.
2) B increments it after A decremented it. So B gets zero and knows the object is invalid. (Edit: Oops, a bug: after B increments refcount, when thread C tries to do same, it would get 1 and conclude the object is valid!)
If B is allowed to allocate the object again (invalid state, refcount == 0), careful synchronization needs to be done remove any races with A's deallocation.
Re:Is reference counting slower than GC?
by barrkel on Tuesday May 24, 2016 @08:06AM
(#11760843)
I think you're hung up on multiple threads reference-counting a single instance. That's not where reference counting as a GC approach gets difficult. It's when you're updating references to values.
Keyword is atomic. Fetch-and-add returns you the previous value atomically.
-------
Edit:
This (below) is obviously a buggy reference counting algorithm.
-------
In freeing (decrementing reference count) thread A, if it was 1 before (returned value) and A added -1, the object can be freed.
Because the operation is atomic, only one of two things can happen:
1) Another reference adding thread B increments it before A decreases it. So A doesn't see 1, thus won't free the object.
2) B increments it after A decremented it. So B gets zero and knows the object is invalid. (Edit: Oops, a bug: after B increments refcount, when thread C tries to do same, it would get 1 and conclude the object is valid!)
If B is allowed to allocate the object again (invalid state, refcount == 0), careful synchronization needs to be done remove any races with A's deallocation.