As with most bugs of this nature, it took dozens of readings through the code to spot it, and by the time I finally realized what I'd done, I felt incredibly stupid. In hindsight it's bloody obvious, but it highlights exactly the kind of mistake that is frighteningly easy to make in concurrent systems.
I'll pose the puzzle here first, and post the solution later. If you figure out my mistake, feel free to say so - but please don't post spoilers :-)
// Step 1: allocate a reference counted resource// Step 2: initialize reference count to 0// Step 3: increment reference count// Step 4: pass resource to an asynchronous (multithreaded/concurrent) procedure// Step 5: increment reference count again// Step 6: pass the same resource to a second asynchronous procedure// Step 7: return from function and wait for the processes to finish// Both asynchronous procedures decrement the reference counter when they complete// When the reference counter hits 0, the resource is deallocatedGood luck!