(simple) boost thread_group question?

I think you problem is caused by the thread_group destructor which is called when your program exits. Thread group wants to take responsibility of destructing your thread objects. See also in the boost::thread_group documentation.

I think you problem is caused by the thread_group destructor which is called when your program exits. Thread group wants to take responsibility of destructing your thread objects. See also in the boost::thread_group documentation.

You are creating your thread objects on the stack as local variables in the scope of your main function. Thus, they have already been destructed when the program exits and thread_group tries to delete them. As a solution, create your thread objects on the heap with new and let the thread_group take care of their destruction: boost::thread *t1 = new boost::thread(threaded_function, 10); ... g.

Add_thread(t1); ...

You should remove the ellipsis between the "new" memory allocation and handing it off to the thread_group. Otherwise if something goes wrong (i.e. Throws) in the intervening code, you will leak the thread.

– John Zwinck Aug 8 '09 at 13:10 Yes, this appears to be the case and was the cause of the bug in the larger program as well. The working example now uses: // launch three threads g. Add_thread(new boost::thread(threaded_function, 10)); g.

Add_thread(new boost::thread(threaded_function, 10)); g. Add_thread(new boost::thread(threaded_function, 10)); – RandomGuy Aug 17 '09 at 16:54 1 A good way to make sure you don't leak it would have been to use std::unique_ptr or similar solution and use ptr.get() to provide the thread to the group_thread. – Klaim Jul 19 at 22:46.

Add_thread() takes ownership of thread you pass in. Thread group deletes the thread. In this example you are deleting memory allocated on stack, pretty much a capital offence.

Member function add_thread() void add_thread(thread* thrd); Precondition: The expression delete thrd is well-formed and will not result in undefined behaviour. Effects: Take ownership of the boost::thread object pointed to by thrd and add it to the group. Postcondition: this->size() is increased by one.

Not sure if that's what's wrong in your code, or if this is just example bug. Otherwise code looks fine.

If you don't need a handle to your threads, try using thread_group::create_thread() which alleviates the need to manage the thread at all: // Snip: Same as previous examples int main(int argc, char* argv) { using namespace std; // launch three threads for ( int I = 0; I.

Related Questions