c++ - how to use std::atomic<> -


i have class wan use in different threads , think may able use std::atomic such this:

classs {     int x;  public:     a()     {         x=0;     }      void add()     {         x++;     }      void sub()     {         x--;     }      }; 

and in code:

  std::atomic<a> a; 

and in different thread:

  a.add(); 

and

  a.sub(); 

but when getting error a.add() not known. how can achieve this?

is there better way this?

edit 1

please note sample example, , want make sure access class threadsafe, can not use

std::atomic<int> x; 

how can make class thread safe using std::atomic ?

you need make x attribute atomic, , not whole class, followed:

class {     std::atomic<int> x;      public:       a() {         x=0;       }       void add() {         x++;       }       void sub() {         x--;       }      }; 

the error in original code normal: there no std::atomic<a>::add method (see here) unless provide specialization std::atomic<a>.

referring edit: cannot magically make class a thread safe using template argument of std::atomic. make thread safe, can make attributes atomic (as suggested above , provided standard library gives specialization it), or use mutexes lock ressources yourself. see mutex header. example:

class   {   std::atomic<int>      x;   std::vector<int>      v;   std::mutex            mtx;    void  add() {     x++;   }   void  sub() {     x--;   }    /* example method protect vector */   void  complexmethod() {     mtx.lock();      // whatever complex operation need here     //  - access element     //  - erase element     //  - etc ...      mtx.unlock();   }    /*   ** example using std::lock_guard, suggested in comments   ** if don't need manually manipulate mutex   */   void  complexmethod2() {     std::lock_guard<std::mutex> guard(mtx);      // access, erase, add elements ...   }  }; 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -