如何以懒惰的方式安全地填充Map线程



假设您有一个Map(编程语言无关紧要(,并希望一点一点地填充它。如果有读写锁对象可用,有人能展示如何使这个线程安全(并行读取、独占写入(吗?

以下是一些不安全的pdeudo代码:


def get_or_create_item(item_id)
if (!@map.has_key?(item_id))
@map[item_id] = create_item()
end
return @map[item_id]
end
def create_item
#...
end

假设您有一个读写锁对象,如何使其线程安全?

rw_lock = ReadWriteLock.new
...
rw_lock.acquire_read()
rw_lock.release_read()
...
rw_lock.acquire_write()
rw_lock.release_write()

感谢

带有读写锁对象的伪代码如下所示:

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            

最新更新