locked
thread question RRS feed

  • Question

  • I have one thread that updates a value (int) in a class. The other thread reads this value. Is it enough to  make this value atomic (atomic<int> value) in order for it to be thread safe? Or do I still need to use a lock (mutex)? Stupid example below...

    class SomeClass {
    public:
       void increaseValue(int newValue) {
           m_value += newValue
       }
    
       int getValue() const {
          return m_value;
       }
    private:
        atomic<int> m_value;
    };
    
    int main() {
       bool run = true;
       SomeClass someClass;
    
       std::thread thr1([&]() {
           while(run) {
            someClass.increaseValue(1);
           }
       })
    
       std::thread thr2([&]() {
           while(run) {
             std::cout << someClass.getValue() << std::endl;
           }
       })
    
       while(true){}
    
    
       return 0;
    }

    Friday, April 12, 2013 3:16 PM

Answers

  • On 4/12/2013 11:16 AM, Anonymous7520 wrote:

    I have one thread that updates a value (int) in a class. The other thread reads this value. Is it enough to  make this value atomic (atomic<int> value) in order for it to be thread safe? Or do I still need to use a lock (mutex)? Stupid example below...

    This program exhibits well-defined behavior, if that's what you are asking. You don't need a mutex, atomic<int> is sufficient to prevent data races.


    Igor Tandetnik

    • Marked as answer by Anonymous7520 Saturday, April 13, 2013 1:02 PM
    Friday, April 12, 2013 3:53 PM