I am reading a book Efficient C++: Performance Programming Techniques Authors is saying following regarding global new and delete operators:
They manage memory in the process context, and since a process may spawn multiple threads,
new()
anddelete()
must be able to operate in a multithreaded environment. In addition, the size of memory requests may vary from one request to the next.
in Chapter 6. Single-Threaded Memory Pooling.
Is this true? I thought C++ does not have a notion of a Multi-threading environment, programmer need to handle is by using some means of mutual exclusion.
Complications due to Concurrency − It is difficult to handle concurrency in multithreaded processes. This may lead to complications and future problems. Difficult to Identify Errors− Identification and correction of errors is much more difficult in multithreaded processes as compared to single threaded processes.
The C++ new and delete operators are thread safe, but this means that a thread may have to wait for a lock on these operations. Once memory is obtained for a thread, the thread_alloc memory allocator keeps that memory available for the thread so that it can be re-used without waiting for a lock.
With multithreading, while the computer system's processor executes one instruction at a time, different threads from multiple programs are executed so fast it appears the programs are executed simultaneously.
First, partitioning a fixed amount of work among too many threads gives each thread too little work that the overhead of starting and terminating threads swamps the useful work. Second, having too many threads running incurs overhead from the way they share finite hardware resources.
It will depend on implementation. For example, Visual C++ runtime had both a single-threaded and a multithreaded version of heap in earlier version, but starting with Visual C++ 2005 it only has a multithreaded version. This MSDN article has a nice summary table.
When a multithreaded heap is used calls to memory allocation and deallocation are thread-safe at expense of additional overhead.
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