In this article we will create a vector thread and discuss things which we need to take care while using it.

Creating & Using vector of std::thread

Let’s Create a vector of std::thread objects i.e.

Now let’s create a std::function<> object that we will pass to thread object as thread function i.e.

Now let’s create 2 thread objects using this std::function objects i.e.

Now, as std::thread objects are move only i.e. we can not copy them, only move them. Therefore, we need to move these 2 thread objects in vector i.e.

We can also push std::thread without specifically specifying std::move(), if we pass them as rvalue i.e.

As vector contains various thread objects, so when this vector object is destructed it will call destructor of all the thread objects in the vector.
If any of the destructed thread object is joinable and not joined then std::terminate() will be called from its destructor. Therefore its necessary to join all the joinable threads in vector before vector is destructed i.e.

Complete example is as follows,

Output:

To compile the above example in linux use,

g++ –std=C++11 example.cpp -lpthread

Use vector<std::thread> cautiously

Move only vector of thread

As thread objects are move only objects, therefore we can not copy vector of thread objects to an another of vector of thread i.e.

It will not compile

Therefore, we can only move vector of thread to an another vector thread i.e.

Changing contents of vector of thread

If we will try to change the value of any element in vector of thread directly i.e.

It will crash our application, because on replacing a thread object inside the vector, destructor of existing thread object will be called and we haven’t joined that object yet. So, it call terminate in its destructor. So, to replace a thread object in vector, we first need to join the existing object and then replace it with new one i.e.

Complete example is as follows,

Output:

To compile the above example in linux use,

g++ –std=C++11 example.cpp -lpthread

 

Click Here to Subscribe for more Articles / Tutorials like this.