C++ Thread, shared data

前端 未结 10 1870
悲&欢浪女
悲&欢浪女 2020-12-04 22:35

I have an application where 2 threads are running... Is there any certanty that when I change a global variable from one thread, the other will notice this change? I don\'t

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 22:51

    Use a lock. Always always use a lock to access shared data. Marking the variable as volatile will prevent the compiler from optimizing away the memory read, but will not prevent other problems such as memory re-ordering. Without a lock there is no guarantee that the memory writes in doSomething() will be visible in the updateScreen() function.

    The only other safe way is to use a memory fence, either explicitly or an implicitly using an Interlocked* function for example.

提交回复
热议问题