And now for some more programming advice. Today I spent a long time trying to track down a bug in my circular buffer implementation. These were the conditions:
- The bug manifested as a buffer entry apparently being 1 number larger than it should be (when writing consecutive integers into the buffer);
- It only showed up when the producer and consumer were in separate processes or threads;
- Whenever it appeared, the consumer had just wrapped around the buffer;
- The problem wasn't to do with insufficient locking.
I'll spare you the painful details: it turned out to be a bug in my test code, in which the test sometimes ended up writing non-consecutive numbers. The wraparound condition, multiprocessing requirement, consistently-being-off-by-one factor? All spurious. The buffer works perfectly and actually seems to be correct even without any locks (though this is because of a happy, but difficult to control, confluence of pro-atomic hardware and compiler factors as I am not explicitly doing atomic locking).
There is no moral for this one (in direct contradiction of the first sentence of this post), apart from "check your test code again" and "Nicholas is an idiot".