线程 for 循环达到它不应该达到的值



我在c++中处理多线程,下面是我的代码:

#include <iostream>
#include <vector>
#include <string>
#include <thread>
void read(int i);
bool isThreadEnabled;
std::thread threads[100];
int main()
{
isThreadEnabled = true; // I change this to compare the threaded vs non threaded method
if (isThreadEnabled)
{
for (int i = 0;i < 100;i++) //this for loop is what I'm confused about
{
threads[i] = std::thread(read,i);
}
for (int i = 0; i < 100; i++)
{
threads[i].join();
}
}
else
{
for (int i = 0; i < 100; i++)
{
read(i);
}
}
}
void read(int i)
{
int w = 0;
while (true) // wasting cpu cycles to actually see the difference between the threaded and non threaded
{
++w;
if (w == 100000000) break;
}
std::cout << i << std::endl;
}

在使用线程的for循环中,控制台以随机顺序ex(5,40,26…(打印值,这是预期的,而且完全可以,因为线程的运行顺序与启动时不同。。。

但让我困惑的是,打印的值有时会超过int i可以达到的最大值(即100(,像80002032274这样的值…也会打印到控制台上,即使i永远不会达到这个数字,我不明白为什么?

此行:

std::cout << i << std::endl;

实际上相当于

std::cout << i;
std::cout << std::endl;

因此,虽然线程安全(意味着没有未定义的行为(,但执行顺序是未定义的。给定两个线程,可以执行以下操作:

T20: std::cout << 20
T32: std::cout << 32
T20: std::cout << std::endl
T32: std::cout << std::endl

这导致控制台中的CCD_ 3(粘贴的数字(和空行。

对此,最简单(不一定是最好的(的修复方法是用共享互斥体包装这一行:

{
std::lock_guard lg { mutex };
std::cout << i << std::endl;
}

(如果std::cout << i << std::endl;是函数中的最后一行,则不需要单独作用域的括号(

相关内容

最新更新