如何以惰性方式安全地填充 Map 线程?
How to fill a Map thread safe in a lazy manner?
假设你有一个地图(编程语言无关紧要)并且想一点一点地填充它。有人可以展示如何在读写锁对象可用的情况下使这个线程安全(并行读取、独占写入)吗?
这里有一些伪代码,它不是线程安全的,可以开始使用:
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()
谢谢
带有 read-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
假设你有一个地图(编程语言无关紧要)并且想一点一点地填充它。有人可以展示如何在读写锁对象可用的情况下使这个线程安全(并行读取、独占写入)吗?
这里有一些伪代码,它不是线程安全的,可以开始使用:
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()
谢谢
带有 read-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