Initializing each thread in vector<thread>
"t" is a vector, you're trying create a thread. It would "work" by doing
t.at(i) = thread(MyFunc, i);
But like @Unimportant said, the way you're doing it is a bit inefficient. If MaxThreads is a really small number like 4, it doesn't matter how you do it but it's good to get into the habit of doing things the right way for when you have bigger vectors of more expensive objects.
When you know the size of the vector you want, it's typically better to call vector.reserve() to allocate all the memory you need upfront instead of doing multiple reallocations as the vector grows. You should also be using vector.emplace_back instead of push_back. emplace_back creates an object directly into the vector instead of creating an object outside then copying/moving it into the vector.
vector<thread> t; t.reserve(MaxThreads); for (int i = 0; i < MaxThreads; i++) { t.emplace_back(MyFunc, i); }
And lastly, don't forget to make your threads unjoinable. Either by calling thread.join() or thread.detach(). If a thread gets destructed while still joinable it will kill your program.

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now