线程之间的同步

时间:2019-04-30 13:12:50

标签: c++ multithreading thread-safety

我是一名学生,我想了解线程之间的同步。

我有两个线程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线程安全吗?

如果不是,优化此代码的最佳方法是什么?

谢谢。

2 个答案:

答案 0 :(得分:1)

  

read_1线程安全吗?

不,它是在何时可以写入该数据的读取。

  

如果不是,优化此代码的最佳方法是什么?

也许使用std::shared_mutex

答案 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,那么您就不会遇到这个问题。

相关问题