Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Threads in a loop

I just tested something like this:

boost::thread workerThread1(boost::bind(&Class::Function, this, ...);
boost::thread workerThread2(boost::bind(&Class::Function, this, ...);

and it works fine. What i now want, is to create as many Threads as i have objects in a list. I have experimentet with boost::foreach and this works fine. But i have problems with the names of the threads.

So simplified the code looks like this:

for
{
    boost:thread name(...);
}

but of course name cant be right here in the loop because it overwrites itself and isnt accessible after the loop. How do i create the threads so that i can join them all after all have been created?

like image 960
Flo Avatar asked Nov 29 '22 15:11

Flo


2 Answers

Why don't you use boost::thread_group? You can create/add/remove threads and join them all (boost::thread_group::join_all()).

boost::thread_group tgroup;
for(...)
{
  tgroup.create_thread(boost::bind(&Class::Function, this, ...)) ;
}
tgroup.join_all();

But be careful about the number threads you are creating, too many threads may lead to OutOfMemory.

like image 188
ali_bahoo Avatar answered Dec 15 '22 06:12

ali_bahoo


Can you not just create a list (or similar) of threads and then just create them and add to the list.

Something like the following (which is likely more pseudo code that anything :-) )

list<boost::thread*> threads;

for
{
    boost::thread* name = new boost::thread(...);
    threads.push_back(name);
}

As mentioned in another answer you can use smart pointers which would be better and you mentioned you have a defined number of threads so an array/vector would be a better choice but as I said the code above isn't perfect anyway

like image 29
Firedragon Avatar answered Dec 15 '22 07:12

Firedragon