Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is dynamic memory allocation in C++11 thread-safe?

Is allocation and deallocation of dynamic memory in C++11 thread-safe? In other words: Can threads use new and delete as freely as single-threaded code?

like image 763
oz1cz Avatar asked Nov 14 '25 10:11

oz1cz


1 Answers

Yes, dynamic allocation by ::operator new and deallocation by ::operator delete is thread-safe. An implementation is however permitted to have a global lock (e.g. on malloc called by new) which would serialize the allocation. If your program redefines ::operator new & ::operator delete it should ensure that they are thread-safe.

Regarding delete you should not delete the same pointer twice (e.g. in two different threads).

like image 58
Basile Starynkevitch Avatar answered Nov 17 '25 08:11

Basile Starynkevitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!