Transaction merging, locks, background threads and performance
Join the DZone community and get the full member experience.Join For Free
the following code is taken from the leveldb codebase :
this code is responsible for merging concurrent transactions. it operates using a mutex and conditional variables. and the idea really impressed me when i first saw it.
i implemented that in voron because i think that this is a great way to gain higher concurrency rates while still having a single writer mode (which is much easier to work with).
however, as it turned out, this isn’t a really good idea in practice. the way conditional variables work, you lock the mutex, check your condition, and then wait on the conditional variable. waking up from a conditional variable means that you have re-acquired the mutex.
what i want to happen:
- multiple concurrent threads will try to write at the same time.
- one of them goes through and start writing, it takes all the pending writes and write them to disk.
- it then releases all the waiting threads whose work it already completed.
- they all move on from there without having to wait on one another.
however, because of the way conditional variables are implemented, what will actually happen is that they each will wake up one at a time, acquiring the mutex lock, then releasing it. however, while they are being released, they compete with one another, and they also compete with the next write .
we profiled this approach, and the result was that we could see how we were spending pretty much all of our time in just synchronizing threads.
instead, we moved to a different approach, in which the first write will actually start off a new thread, dedicated to writing batches. the way it works, when a thread want to write a batch, it will add that to a queue and wake up the background writer thread, then wait on an event. the background writer will read all the current batches and merge them into a single write transaction.
when it is done, it will wake up all the sleeping writers. we tried to use taskcompletionsource for that, initially, but we found that the inline nature of tasks made that too expensive to use. instead, we use manualreseteventslim, and we explicitly wait / wake them. we even reuse events, so we don’t have to keep creating and disposing them.
the end result is that we have a pretty sequential process for actually doing concurrent writes, which turn it into a simple producers/consumer problem from threading perspective, and the actual writes into a simple write things out as fast as you can process them.
this also gives us the chance to do some re-ordering of operations to get better performance overall.
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.