Volatile and CreateThread

前端 未结 6 448
借酒劲吻你
借酒劲吻你 2020-12-06 07:52

I just asked a question involving volatile: volatile array c++

However my question spawned a discussion on what volatile does.

Some claim that w

6条回答
  •  情深已故
    2020-12-06 08:54

    It's worse than you think, actually - some compilers may decide that that loop is either a no-op or infinite loop, eliminate the infinite loop case, and make it return immediately no matter what done is. And the compiler is most certainly free to keep done in a local CPU register and never access its updated value in the loop. You must either use appropriate memory barriers, or a volatile flag variable (this technically isn't enough on certain CPU architectures), or a lock-protected variable for a flag like this.

提交回复
热议问题