Search code examples
c++multithreadingboostthreadgroup

Encapsulated boost thread_group. Questions about ids and synchronization


I´m using a class that encapsulates a thread_group, and have some questions about it

class MyGroup{

private:
     boost::this_thread::id _id;
     boost::thread::thread_group group;
     int abc;
     //other attributes
public:

     void foo();


};

In the class constructor, i launch N threads

for (size_t i=0;i<N;i++){
      group.add(new boost::thread(boost::bind(&foo,this)));
}


void foo(){

   _id = boost::this_thread::get_id();
   //more code.
   abc++ //needs to be sync?
}

So, here are my questions.

Do class attributes need to be synchronized?

Do every thread get a different id? For example, if I have

void bar(){
  this->id_;
}

will this result in different ids for each thread, or the same for everyone?

Thanks in advance !


Solution

  • Yes, shared data access must be protected even if you use thread creation helpers as boost.

    In the end they all will execute the same code at the same time, and there is nothing a library can do to put protection around a variable you own and you manage.

    If this->_id prints the current thread id then yes, it will print different values while different threads access it.