gpt4 book ai didi

c++ - int 变量的并发递增

转载 作者:IT老高 更新时间:2023-10-28 22:32:59 27 4
gpt4 key购买 nike

面试中的一个问题

int count = 0;

void func1()
{
for ( int i =0 ; i < 10; ++i )
count = count + 1;
}

void func2()
{
for ( int i =0 ; i < 10; ++i )
count++;
}

void func3()
{
for ( int i =0 ; i < 10; ++i )
++count;
}

int main()
{
thread(func1);
thread(func2);
thread(func3);

//joining all the threads

return 0;
}

问题是:count 理论上可能取的值范围是多少?上限显然是 30,但下限是多少?他们告诉我这是 10,但我不确定。否则,我们为什么需要内存屏障?

那么,范围的下限是多少?

最佳答案

这是未定义的行为,所以 count 可以取任何值可以想象。否则程序可能会崩溃。

关于c++ - int 变量的并发递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16416843/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com