我是一名学生,我想了解线程之间的同步。
我有两个线程t1和t2。
我之间有一块共享的记忆。
/*e.g.*/ std::map<std::string, std::string> data;
一个线程,假设t1正在读取数据,另一个线程正在写入。.
std::mutex mu; //is used for synchronization
std::string read_1(std::string key)
{
return data[key];
}
std::string read_2(std::string key)
{
mu.lock();
return data[key];
mu.unlock();
}
void write(std::string key, std::string value)
{
mu.lock();
data[key] = value;
mu.unlock();
}
read_1线程安全吗?
如果不是,优化此代码的最佳方法是什么?
谢谢。
答案 0 :(得分:1)
答案 1 :(得分:1)
不。 read_1
是不是线程安全的。它需要在访问data
之前锁定互斥锁。
这会很安全;
std::string read_1(std::string key)
{
std::lock_guard<std::mutex> guard(mu);
return data[key];
}
也;您的read_2
函数已损坏。它会在解锁互斥锁之前返回。如果您使用过std::lock_guard
,那么您就不会遇到这个问题。