Avinash
Avinash

Reputation: 13267

new and delete handles multithreading issues

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() and delete() 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.

Upvotes: 6

Views: 3390

Answers (3)

sharptooth
sharptooth

Reputation: 170519

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.

Upvotes: 7

imreal
imreal

Reputation: 10378

As of C++11 (which has the concept of a data race) the standard guarantees that new/delete, calloc/malloc/realloc/freewill occur in a single total order.

From n3690 18.6.1.4:

For purposes of determining the existence of data races, the library versions of operator new, user replacement versions of global operator new, the C standard library functions calloc and malloc, the library versions of operator delete, user replacement versions of operator delete, the C standard library function free, and the C standard library function realloc shall not introduce a data race (17.6.5.9). Calls to these functions that allocate or deallocate a particular unit of storage shall occur in a single total order, and each such deallocation call shall happen before (1.10) the next allocation (if any) in this order.

I could not find any such guarantees in previous versions of the standard, but (like others have said) I believe most implementations provide multi-threading support for memory allocation.

Upvotes: 0

iammilind
iammilind

Reputation: 70068

C++ (C++03 standard) doesn't talk about multi-threading. However most of the platforms support thread-safe new/malloc. Here is a previous post discussing same kind of question.

In C++11, the threads are introduced.

Upvotes: 3

Related Questions