Is it safe to read an integer variable that's being concurrently modified without locking?

前端 未结 12 1342
青春惊慌失措
青春惊慌失措 2020-12-02 09:03

Suppose that I have an integer variable in a class, and this variable may be concurrently modified by other threads. Writes are protected by a mutex. Do I need to protect re

12条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 09:39

    If a variable is marked with the volatile keyword then the read/write becomes atomic but this has many, many other implications in terms of what the compiler does and how it behaves and shouldn't just be used for this purpose.

    Read up on what volatile does before you blindly start using it: http://msdn.microsoft.com/en-us/library/12a04hfd(VS.80).aspx

提交回复
热议问题