Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

main thread and thread pools

The standard idiom seems to be to create n = std::thread::hardware_concurrency() threads and place them into a thread pool. But the main thread is a thread like any other, hence we might create just n - 1 threads and consider the main thread a part of the thread pool and save some resources. Is there any reason why this should not be done?

like image 470
user1095108 Avatar asked Dec 26 '20 10:12

user1095108


People also ask

What is the difference between thread and thread pool?

A thread pool is a collection of threads which are assigned to perform uniformed tasks. The advantages of using thread pool pattern is that you can define how many threads is allowed to execute simultaneously.

What is a thread pool thread?

A thread pool is a collection of worker threads that efficiently execute asynchronous callbacks on behalf of the application. The thread pool is primarily used to reduce the number of application threads and provide management of the worker threads.

Why do we need a thread pool?

A thread pool helps mitigate the issue of performance by reducing the number of threads needed and managing their lifecycle. Essentially, threads are kept in the thread pool until they're needed, after which they execute the task and return the pool to be reused later.


Video Answer


1 Answers

If you do computation in the main thread as well, then sure.

But more often than not the idiom that I see is that the main thread dispatches the work into the thread pool and then just waits for the thread pool to finish. If that wait is not done with busy-waiting, but something like a condition_variable, then it does not occupy a processor core for very long.

It is also common for the main thread to be used to handle operating system signals. Especially in the case of a UI application the main thread needs to be kept responsive, so using it for potentially longer running tasks leads to a bad user experience.

like image 57
PeterT Avatar answered Oct 19 '22 14:10

PeterT