gpt4 book ai didi

c++ - 在多线程环境中从 STL Map 读取/写入

转载 作者:太空宇宙 更新时间:2023-11-03 10:35:49 25 4
gpt4 key购买 nike

问题:我需要编写一个函数来返回映射中输入键的值。如果函数在 map 中找不到值,它将从数据库中获取值,写入 map 以供将来使用并返回相同的值。可以有多个线程调用此函数。

我在考虑这一行:

string GetData (const int key)
{

pthread_rwlock_rdlock(&rwlock); //read lock
string result = "not found";
my_map::const_iterator iter = m.find(key);
if ( iter != m.end() )//found
{
result = iter->second;
}
else //missing
{
pthread_rwlock_wrlock(&rwlock); // write lock
//fetch value from data base


//if successful, add to the map
m[key] = "missing data";
result = "missing data";
pthread_rwlock_unlock(&rwlock); // unlock write lock
}
pthread_rwlock_unlock(&rwlock); // unlock read lock
return result;
}

这个函数线程安全吗?两个或多个线程不可能在写锁上排队并从数据库中查询相同的键吗?如果是,我怎样才能避免这种情况?

最佳答案

这个函数不是线程安全的,因为它会导致未定义的行为。当您尝试获取写锁时,您已经持有读锁。来自 the documentation for pthread_rwlock_wrlock:

Results are undefined if the calling thread holds the read-write lock (whether a read or write lock) at the time the call [to pthread_rwlock_wrlock] is made.

此解决方案也不是异常安全的。如果在持有锁时抛出异常,则锁不会被释放,你的应用程序无疑会死锁。您应该使用 C++ 线程库(Boost.Thread、OpenThreads、just::thread 或类似的东西),它提供面向 C++ 的设计,支持诸如 scoped_lock(或 lock_guard).

为了使算法正确,您需要遵循以下原则:

obtain read lock
attempt to find object
if object exists
return object
else
release read lock
obtain write lock
if object exists
return object
else
insert object
return object

[如果你使用某种lock_guard,你不需要担心返回时释放持有的锁]

关于c++ - 在多线程环境中从 STL Map 读取/写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3836536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com