Make reference counting be threadsafe

Also detect underflow of the reference count
Document the atomics API
Fix some warnings found by compiling with higher optimizations