Wednesday, October 28, 2009

reference counting

reference counting can be thought of as a shared lock in many cases. especially in situations where a zero reference event means something.

this is because thinking of a lock this way makes you realize that taking out a reference is simular to acquiring a resource shared. this is important when a function ends up holding resources while the reference is held. this then inherently creates a locking order.

this opens us up to incorrect locking order, just by incrementing a ref count:

thread 1: function A

acquires resource R
waits for refcount X to reach zero : equiv to acquiring SR lock exclusive

thread 2: function B

increments X : equiv to aquiring SR lock shared
acquires R

in the above example it is possible to deadlock both thread indefinately since thread 2 will never get resouce R and thread 1 may never get notified of the zero ref event.

To make this complete we need to remark that a ref count is more like a SR lock that also supports try acquire exclusive. This is best represtented in a referenced object that decrements its refcount in a container classes destructor. And when the ref goes to zero it frees up its associated memory. This is simular to the destructor trying to acquire the SR lock exclusive and if successful freeing up the associated memory.

5 comments: