I have multiple threads processing events. I want to assign a nanosecond timestamp to each event. It must be a unique id, though. So, in the odd case that two events arrive such that they would be assigned the same timestamp, I want one of them to be incremented by one nanosecond. Given that the real precision is not at the nanosecond level, that’s ok as far as the time stamp nature of the system.
In one thread, this is a trivial problem. But across multiple threads, it gets more challenging. Performance is absolutely critical so the idea of naively synchronizing on a typical id generator type of thing seems like it would block far too much.
Is there some approach that solves this with minimal or no locking?
You can use
atomicModifyIORefto implement an atomic counter. With GHC, it’s implemented using atomic operations, not locks.