Concurrency Puzzle 12/01/2011
The last thing the world probably needs is more examples of my incompetence, but in case you needed just one more, here's a pretty good example: As you can probably tell, you're looking at some good old fashioned C. I had some struct with a field counter, and I needed to write a function that would increment that counter and return the incremented value, all atomically. This was my first solution and it's very, very wrong. It avoids some of the worst pitfalls of a multithreaded counter, in that the output does at least increase monotonically and there won't be any nasty memory corruption. At the same time, it's not only possible but likely that two concurrent calls to this function will return the same value. Each will perform the highly optimized, blisteringly fast atomic increment, then dopily retrieve and return the same value from o->counter. In other words, this function is kind of atomic, which as my concurrency professor used to say is a bit like being kind of a virgin. The puzzle is how to fix it. With locks or multiple concurrency operations the answer is trivial, but with only one hardware-level concurrent operation it's at least not immediately obvious to me how to do it. The basic problem is that you need to do two atomic things at once: increment the value of o->counter and write that atomically-incremented value to the return register. Almost sure that it is a laughably naive answer, I propose this solution: Not something I would necessarily bring to a Google interview, but it gets the job done. If you've got a better solution I'd love to hear about it. CommentsLeave a Reply | Sam TarakajianBreakfast is a faith-based initiative ArchivesJanuary 2012 Categories |
RSS Feed