I'm trying to understand the different use cases. and the difference between the 2 thread uses.
This is a great tutorial I have read which explains boost::thread_group
.
and here is a code I'm using:
boost::threadpool::pool s_ThreadPool(GetCoreCount());
CFilterTask task(pFilter, // filter to run
boost::bind(&CFilterManagerThread::OnCompleteTask, this, _1, _2) // OnComplete sync callback // _1 will be filter name // _2 will be error code
);
// schedule the new task - runs on the threadpool
s_ThreadPool.schedule(task);
this is the destructor:
s_ThreadPool.wait(0);
can you please explain?
boost::thread_group
is a convenience class for performing thread management operations on a collection of threads. For example, instead of having to iterate over std::vector<boost::thread>
, invoking join()
on each thread, the thread_group
provides a convenient join_all()
member function.
With boost::thread
, regardless of it being managed by boost::thread_group
, the lifetime of the thread is often dependent on the work in which the thread is doing. For example, if a thread is created to perform a computationally expensive calculation, then the thread can exit once the result has been calculated. If the work is short-lived, then the overhead of creating and destroying threads can affect performance.
On the other hand, a threadpool is a pattern, where a number of threads services a number of task/work. The lifetime of the thread is not directly associated with the lifetime of the task. To continue with the previous example, the application would schedule the computationally expensive calculation to run within the thread pool. The work will be queued within the threadpool, and one of the threadpool's threads will be selected to perform the work. Once the calculation has completed, the thread goes back to waiting for more work to be scheduled with the threadpool.
As shown in this threadpool example, a threadpool can be implemented with boost::thread_group
to manage lifetime of threads, and boost::asio::io_service
for task/work dispatching.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With