gpt4 book ai didi

c++ - 如果跨线程共享变量,将变量标记为 volatile 有用吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:56:00 28 4
gpt4 key购买 nike

<分区>

Notice!

I'm obviously failing to make my point clearly to everyone here, and it's incredibly frustrating. My goal was to dispel the myth that volatile is effectively a no-op, that it does nothing. I was not trying to state that it should be used, that it is essential, that it is not redundant, etc.

I have shown that volatile does still do a thing. I concede that it is redundant under certain circumstances, and that the multi-threaded example was a poor choice.

I am also not trying to hide the fact that my answer's initial revisions contained errors. But this Q&A is not even coming close to fulfilling its intended purpose. To that end, I think it's time to chuck it away.

Thanks to Kerrek and T.C. for their insights. I just don't think their responses fit the question that I wanted to ask. I'm sure that's my fault for asking it poorly.

Therefore I am abandoning it! And closing it as a duplicate of the question not that it was intended as, but that it has been interpreted as.

Cheers! (& hth.)

我在一个线程中写入一个变量并在另一个线程中读取它。我被告知 volatile 对此完全没用,除非我在使用硬件,否则我不需要在这个时代使用它。

int x = 0;
void thread1()
{
while (true) {
sleep(1);
if (x > 0)
break;
}
}

void thread2()
{
while (true) {
sleep(1);
x++;
}
}

在这种情况下,使用 volatile 有什么好处吗?
如果 x 不是简单的 int 而是类类型呢?

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