|
Boost Users : |
Subject: Re: [Boost-users] Fwd: boost::thread and corresponding stack array
From: Anthony Williams (anthony.ajw_at_[hidden])
Date: 2010-06-07 05:29:39
Aditya Arora <callmeadi_at_[hidden]> writes:
> I'd like to use boost threads, if possible, in an upcoming project, just for
> the sake of portability. Â The problem is that boost threads seem a bit unwieldy
> when it comes to quickly creating multiple threads. Â Since the thread object
> constructor is what actually launches the thread, you can't simply create an
> array of thread objects on the stack, since each thread is only launched when
> the constructor is passed a functor. Â Therefore, if you want an array of
> threads, you need to allocate each thread object individually on the heap,
> like:
>
> boost::thread* thr[SIZE];
> for (int i = 0; i < SIZE; ++i) thr[i] = new boost::thread(functor);
That works, but is unwieldy due to the "new" and the need to call
delete. Thankfully it's not the only way. With the move support you can
write the following:
boost::thread thr[SIZE];
for (int i =0 ; i < SIZE: ++i) thr[i] = boost::thread(functor);
The thread objects are created without a thread, then you create a new
thread object with a new thread and transfer that to the appropriate
element of the array.
You will still need to join your threads individually though as the
destructor calls detach().
Anthony
-- Author of C++ Concurrency in Action http://www.stdthread.co.uk/book/ just::thread C++0x thread library http://www.stdthread.co.uk Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk 15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK. Company No. 5478976
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net