Make refcounting atomic
Merge pull request #1497 from carlosmn/atomic-refcount

Make refcounting atomic