c++ - 同时读写时输出不一致

标签 c++ multithreading synchronization

为什么这段代码会产生不一致的读取函数输出?

#include <cstdio>
#include <thread>
#include <mutex>

std::mutex mu;
int i = 0;

void writeThread()
{
    for (int j = 0; j < 1000; ++j)
    {
        std::lock_guard<std::mutex> lock(mu);
        printf ("write i: %d\n", ++i);
    }
}

void readThread()
{
    for (int j = 0; j < 1000; ++j)
        printf ("Read i = %d\n", i);
}

int main()
{
    std::thread t(writeThread);
    std::thread z(readThread);
    t.join();
    z.join();
    return 0;
}

我有时会得到类似的东西:

write i: 996
write i: 997
Read i = 980 <--- wrong reader output starting here
Read i = 998
Read i = 998
write i: 998
Read i = 998
write i: 999
Read i = 999

只是输出错误还是我真的需要在读取器函数中使用互斥量?

最佳答案

Is only the output wrong or do I really need a mutex in the reader function?

输出没有错,如果您有两个或多个线程访问一个变量,并且其中至少一个是写入器,那么您需要提供同步。自 readThread不等待 WriteThread写信给 i你有比赛条件。这是未定义的行为,您获得的任何输出都是“正确的”。要解决此问题,您需要添加 std::lock_guard<std::mutex> lock(mu);readThread喜欢

void readThread()
{
    for (int j = 0; j < 1000; ++j)
    {
        std::lock_guard<std::mutex> lock(mu);
        printf ("Read i = %d\n", i);
    }
}

如果你有更多的读者然后你有作家你可以使用 std::shared_mutex 这将允许多个读者同时阅读,但会在其中一位作者需要写作时阻止所有读者和其他作者。

关于c++ - 同时读写时输出不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44456763/

相关文章:

java - 可重入锁可以完全替代同步吗?

php - 拉维尔 5 : syncing an extra field via pivot

javascript - Ajax异步: false freezes web page during loading in slow network

c++ - OpenCV 错误 : "LINK : fatal error LNK1104: cannot open file ' opencv_core231d. 库'”

c++ - 模板 :Name resolution -->can any one tell an other example for this statement. ..请

android - ASyncTasks 阻止其他人

c++线程不执行

C++ Bimap 左 unordered_map 右排序可变 multimap

c++ - 当对象超出范围时,C++ 会调用析构函数吗?

c# - 并行数据处理混淆了一些信息