【发布时间】:2019-04-30 13:12:50
【问题描述】:
我是一名学生,我想了解线程之间的同步。
我有两个线程 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 它是线程安全的吗?
如果不是优化此代码的最佳方法是什么?
谢谢。
【问题讨论】:
-
不,
read_1不是线程安全的。我不确定“这段代码”是什么代码——你没有展示太多。 -
另外,
read_2已损坏 - 它锁定互斥锁,但不解锁。mu.unlock()永远无法到达。这将很快导致未定义的行为。 -
使用
std::unique_lock之类的东西,而不是手动锁定/解锁互斥锁。 -
data未定义 ... -
只需阅读
<mutex>标头
标签: c++ multithreading thread-safety