Suppose I have a Map (programming language doesn't matter) and would like to fill them up bit by bit. Can someone show how to make this thread-safe (parallel reads, exclusive writes) given read and write locks available?
Here's some pdeudo-code, which is not threadsafe, to get started:
def get_or_create_item(item_id)
if ([email protected]_key?(item_id))
@map[item_id] = create_item()
end
return @map[item_id]
end
def create_item
#...
end
How to make it thread-safe, assuming you have
read_lock.lock()
read_lock.release()
write_lock.lock()
write_lock.release()
available?
Thanks
CodePudding user response:
Pseudocode with a read-write lock object would look like this:
ReaderWriterLock rwLock // initially unlocked
getOrCreate(id)
// try getting
rwLock.acquireRead()
optional res = map[id]
rwLock.releaseRead()
if (res.hasValue)
return res
// since we are here, the item isn't in the map
rwLock.acquireWrite()
res = map[id]
// check again if another thread inserted the item while we were waiting for the write lock
if (!res.hasValue)
res = createItem()
map[id] = res
rwLock.releaseWrite()
// at this point res must have a value
return res