mardi 5 février 2019

Questions about std::thread class

Considering the following class header:

class ThreadClass {
public:
  ThreadClass();
  ~ThreadClass();
  void operator()(int val);
  void set(int val);
  int get();
private:
  int x;
};

And the following implementation:

ThreadClass::ThreadClass(): x(0) {
  std::cout << "Constructing..." << std::endl;
}
ThreadClass::~ThreadClass() {
  std::cout << "Destructing..." << std::endl;
}
void ThreadClass::operator()(int val) {
  set(val);
  std::cout << get() << std::endl;
  set(val * 2);
  std::cout << get() << std::endl;
}
void ThreadClass::set(int val) {
  x = val;
}
int ThreadClass::get() {
  return x;
}

Launching the following main, class destructor is called several times instead of one:

int main(int argc, char const *argv[]) {
  std::thread x = std::thread(ThreadClass(), 10);
  x.join();
  return 0;
}

>>> Constructing...
>>> Destructing...
>>> Destructing...
>>> 10
>>> 20
>>> Destructing...

Since my knowledge about the std::thread class is not so deep, I would like to ask you:

  1. why this happens? Sincerely, I was expecting just a single instance of the ThreadClass.
  2. In order to avoid unexpected behaviour, is it necessary to overload some of the class operators?

Aucun commentaire:

Enregistrer un commentaire