User2021
User2021

Reputation: 49

C++ initialization of a thread in a constructor

Given this code in C++:


#include <vector>
#include <thread>

class MyClass {
    std::thread workerThread;
    std::vector<int> vec;
public:
     MyClass(): 
     workerThread(&MyClass::myLoop, this),
      vec(){}

}

void MyClass::myLoop() {
   int x= 0;
   for (size_t i=0; i < vec.size(); ++i) {
      x = vec[i];
   }
} 

Is it possible that when creating instance of type MyClass the worker thread will that is created in the constructor will start executing the myLoop function before vec is initialized resulting in undefined behavior?

Upvotes: 0

Views: 49

Answers (0)

Related Questions