Torbilicious
Torbilicious

Reputation: 467

Creating vector<thread>

I am simply trying to create a std::vector of threads and run them.

Code:

thread t1(calc, 95648, "t1");
thread t2(calc, 54787, "t2");
thread t3(calc, 42018, "t3");
thread t4(calc, 75895, "t4");
thread t5(calc, 81548, "t5");

vector<thread> threads { t1, t2, t3, t4, t5 };

Error: "function std::thread::thread(const std::thread &)" (declared at line 70 of "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\thread") cannot be referenced -- it is a deleted function

thread(const thread&) = delete;

What seems to be the problem?

Upvotes: 0

Views: 313

Answers (3)

Jarod42
Jarod42

Reputation: 218323

You may use:

vector<thread> threads 
{ 
    std::move(t1),
    std::move(t2),
    std::move(t3),
    std::move(t4),
    std::move(t5) 
};

Upvotes: 3

Stefan Weiser
Stefan Weiser

Reputation: 2292

Copying of thread objects is forbidden. Moving is allowed. But you can use a shared_ptr to solve this.

My favorite way to use vectors of threads is via shared pointer.

std::vector<std::shared_ptr<std::thread>> threads;

Using them in this way lets always enough flexibility to extend the vector (vectors are used to be extensible).

threads.push_back(std::shared_ptr<std::thread>(new std::thread(&some_fn)));

For your code this would look like:

using namespace std;

shared_ptr<thread> t1 = make_shared<thread>(calc, 95648, "t1");
shared_ptr<thread> t2 = make_shared<thread>(calc, 54787, "t2");
shared_ptr<thread> t3 = make_shared<thread>(calc, 42018, "t3");
shared_ptr<thread> t4 = make_shared<thread>(calc, 75895, "t4");
shared_ptr<thread> t5 = make_shared<thread>(calc, 81548, "t5");

vector<shared_ptr<thread>> threads { t1, t2, t3, t4, t5 };

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477640

Since threads aren't copyable, but movable, I recommend the following approach:

std::vector<std::thread> threads;

threads.emplace_back(calc, 95648, "t1");
threads.emplace_back(calc, 54787, "t2");
threads.emplace_back(calc, 42018, "t3");
threads.emplace_back(calc, 75895, "t4");
threads.emplace_back(calc, 81548, "t5");

Upvotes: 5

Related Questions