I'd like to use Boost to create n threads, each invoking a method on an object, and then join_all to wait for them all to complete. I'd expect this would be simple using thread_group and join_all, but I'm confused about the following:
While
threadallows passing an object and method,thread_group::create_threaddoesn't. This can be worked around (as in How to pass function parameters to boost::thread_groups::create_thread() ), but I'm not sure if there's a reason for that difference; if there is, I'd like to know what the rationale is before I steamroll through it.I'm not sure about scope and lifetime of both the thread and the object I'm passing it. My understanding is that with simple threads, both the
threadand the passed object can go out of scope with no problem: the actual system thread stays running, and the passed object is copied. But, here again,thread_groupseems to complicate this, especially if I need to usenew(as per that workaround referenced above).Finally, if I do use
new, who does thedelete? I've tried to figure out how to use a smart pointer, but then the delete seems to happen in the for loop, before thejoin_allcall.
My code so far is:
for (int i = 0; i < numThreads; i++) {
W w = W(...);
//threadGroup.create_thread(&W::work, &w); // Won't work, create_thread won't take params
boost::thread(&W::task, w);
}