Why is creating a new thread expensive?

I read a lot of .Net resources telling me that I should use a thread pool thread and not instantiate a new thread. They say you have to do this because creating a new thread is an expensive operation. What happens when creating threads, which makes it expensive?

+4
source share
4 answers

Everything is relative. Creating a new thread is expensive ... compared to not creating it. If you do not do a lot of work on a thread, the work of creating and breaking threads can potentially become a measurable part of your processor. But it's cheap to create a new process, especially on Windows.

It is also better to use threadpool because it is configured to help you avoid too many threads at the same time. You rarely want more than a few threads active at a time, or you will spend a lot of time doing context switches between them. Using threadpool manages this for you, since additional requests are queued until the workflow is ready.

+16
source

Each thread defaults to 1 MB of allocated memory. It can quickly become expensive.

+4
source

There are several factors. One of them is referred to as stack memory. Since the stack memory is not processed by the usual GC allocator used for objects, creating a thread stack and then abandoning it is very different from creating mega objects of a heap of objects and their failure.

Another factor not yet mentioned is the costs associated with things such as threaded variables. On some systems that require all the static flow variables that a thread can use to determine before the flow starts, starting a new thread will require initialization of all static variable flows. Because .net allows streams to dynamically add stream variables, the data structures used are different. However, initializing such data structures when starting a stream is not free.

+1
source

Threadpool is not only the amortization of the costs of creating and destroying threads, and not just the storage of memory with fewer stacks. The real advantage of this is to avoid too many active threads at the same time and minimize context switches when starting the server application. Even if you are not writing a server application, threadpool is simply better abstracting than a thread, start an asynchronous operation, get a notification when finished, or call back when you're done, and let the OS or runtime determine the number of threads to create.

+1
source

Source: https://habr.com/ru/post/1347613/


All Articles