为什么这段代码会产生不一致的读取函数输出?
#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/