• entries
627
1447
• views
1008930

# Concurrent programming is hard, mmmkay?

1161 views

Here's a fun bug that I've had in one of my projects for quite some time, which I finally figured out and fixed today.

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!

I think I see it, message away!

Concurrent programming IS hard.

I always remember to never make any assumption about the order of events, and to guarantee that the order of how I want things to happen should happen! Of course that's easier said than done...

I think I see two mistakes, sent a PM.

Both have been denied as the problem and not bugs.

## Create an account

Register a new account