Thursday, March 16, 2023

Effective usage of locks in multi-threading

In an application with multiple threads and shared resources, make sure that you lock sections that have the minimal time impact, because other threads have to wait for the lock to be released. Let's say you have a function that saves a buffer to a file:

function saveData(newData) {
    addToBuffer(newData)
    saveBufferToFile()
}
To make this function thread safe, you might haphazardly lock at the beginning and unlock at the end of function:
function saveData(newData) {
    lock()
    addToBuffer(newData)
    saveBufferToFile()
    unlock()
}
Since saving buffer to file on disk takes a lot of time, another thread that wants to add to the buffer has to wait for file operation to finish. To decrease wait time of other locks that call saveData function, lock before adding to buffer and unlock before saving to file:
function saveData(newData) {
    lock()
    addToBuffer(newData)
    unlock()
    saveBufferToFile()
}