aso
aso

Reputation: 1316

C++ threading - spawn an object (class) in loop?

I need to spawn class object. For example:

class Worker {
  Worker(int arg1, Object *obj);
  void workLoop() { while(true) { ... } }
}

And I need spawn in loop threads with creating objects. When I do this "static", it works:

thread th1(&Worker::workLoop, Worker(args...));
thread th2(&Worker::workLoop, Worker(other args...));

But I can't spawn this in loop. I tried:

for (...) {
  thread th(&Worker::workLoop, Worker(...));
  threadsVector.push_back(std::move(th));
}

...but only first thread works.

Also, I have in Worker class this:

std::thread spawn() {
    return std::thread(&Worker::workLoop, this);
}

I don't know how do this and why loop can't spawn my threads correctly.

Upvotes: 1

Views: 822

Answers (1)

czifro
czifro

Reputation: 784

try this

class Worker{
   Worker(int arg, Object *obj)
   void workLoop() { while(true) { ... } }
}; // do not forget the semicolon

....

vector<thread> pool;

auto func = [](Worker w){
     w.workLoop();
};

// example with thread
for (int i = 0; i < 5; ++i)
   pool.push_back(thread(func, Worker(5, obj)));

for (int i = 0; i < pool.size(); ++i)
   pool[i].join();
// example

create a lambda expression that takes in a worker object and calls the workLoop method inside then you can pass the lambda as an object and pass it an argument inside the thread constructor

Upvotes: 3

Related Questions