Moving threads & using [] operator

Hi
I have a class that contains a vector of threads called m_threads.

I thought the best way to initialize them would be like this:

(constructor of my class)
1
2
3
4
5
6
7
8
9
10
11
12
ThreadPool::ThreadPool(uint threads):
  m_nThreads{threads},
  m_stopFlag{false}
{

  m_threads.reserve(m_nThreads);

  for(auto i = 0u; i < m_nThreads; i++)
    m_threads[i] = std::move( std::thread{ [=]{} } );

}

(rather than push_back() - because that may resize the vector multiple times (right?) )

It compiles fine but crashes with the following message when i run it:
 
This application has requested the Runtime to terminate it in an unusual way.


I dont understand what is wrong with it, can somebody explain it to me?
(Im pretty sure the crash happens when it tries to move the thread into the vector - The destructor joins each thread in the vector btw)



Also:
i would really like to have a private function in my class called something like worker() that each thread runs (rather than a long lambda) - is that possible? (i tried simply passing worker as an argument to the threads but that gives me a compilation error - i guess you cant pass private member functions to threads. Is there a way around this? )

Thank you
Last edited on
reserve does not change the size of the vector. It just make sure the vector allocates enough space to store that many elements, so that it won't have to do any further reallocations as long as the size stays below the specified capacity.

So if you use reserve you must use push_back (or similar) functions to insert the threads.

If you want to use the subscript operator [] and assign the threads you should have used resize instead of reserve. Note that std::move is not necessary because the thread objects that you create are already rvalues.
ohh, sorry i should have read up on the function before i used it. Thanks alot :)

(if anybody knows how to make the threads execute a private member function, rather than a lambda, i would also really like to know that :p )
Last edited on
And as for using member functions with std::thread you can do that by passing a pointer to the member function as the first argument, a pointer to the object as second argument, and if the function expects arguments you just pass them as third argument, fourth argument, and so on...

 
std::thread(&ThreadPool::worker, this)
Topic archived. No new replies allowed.