Safe to use volatile bool to force another thread to wait? (C++)

后端 未结 5 1695
醉话见心
醉话见心 2021-02-08 18:52

Everything I\'ve read about volatile says it\'s never safe, but I still feel inclined to try it, and I haven\'t seen this specific scenario declared unsafe.

I have a sep

5条回答
  •  天命终不由人
    2021-02-08 19:01

    Depending on the architecture being cache-coherent (e.g. x86 processors) I expect this will work just fine. You may find that either of your two threads may run for an iteration more than if you use true atomic operations, but since only one side is setting vs. reading the values, there is no requirement for true atomic operations.

    However, if the processor (cores) that are executing the code require specific cache-flushing to make the "other core(s)" see the updated value, then you may be stuck for some time - and you would need proper atomic updates to ensure the other processor's cache is invalidated.

    I'm assuming that renderer->render() takes a fair amount of time, so reading the stillRendering shouldn't affect the overall runtime much at all. volatile typically just means "please don't put this in a register and keep it there".

    (You probably need programRunning to be a volatile too!)

提交回复
热议问题