If I allocate memory in one thread in C++ (either new or malloc) can I de-allocate it in another, or must both occur in the same thread? Ideally, I'd like to avoid this in the first place, but I'm curious to know is it legal, illegal or implementation dependent.
Edit: The compilers I'm currently using include VS2003, VS2008 and Embedded C++ 4.0, targetting XP, Vista, Windows 7 and various flavours of Windows CE / PocketPC & Mobile. So basically all Microsoft but across an array of esoteric platforms.
In a multi-threaded process, all of the process' threads share the same memory and open files. Within the shared memory, each thread gets its own stack. Each thread has its own instruction pointer and registers.
New and Delete Operator In C++ when we want to allocate memory from the free-store (or we may call it heap) we use the new operator. int *ptr = new int; and to deallocate we use the delete operator.
The answer is simple: all threads in C share the same address space. This means all memory, the heap included, is shared between all threads.
Sometimes there just isn't enough memory, meaning that malloc isn't guaranteed to return a pointer to usable memory. If it isn't able to allocate memory, it will return a null pointer, NULL .
Generally, malloc/new/free/delete on multi threaded systems are thread safe, so this should be no problem - and allocating in one thread , deallocating in another is a quite common thing to do.
As threads are an implementation feature, it certainly is implementation dependant though - e.g. some systems require you to link with a multi threaded runtime library.
There's nothing about new/delete themselves that prevent you from allocating and deallocating in separate threads. As many have said, the Standard is silent on multi-threading -- there is neither support for multi-threading, nor is there anything preventing you from doing it using any of the standard facilities. This is both good and bad in that you can do anything you want, but the language provides no direct mechanism to help you do it safely.
There are many potential technical issues you may need to contend with however. Many compilers have multi-threaded- and single-threaded flavors of the runtime libraries that implement new & delete, so you must be sure you use the right one. (VS 2008 has done away with the single-threaded CRT, so this is not an issue there.) More importantly, your software must be designed from the ground up to be multi-thread aware, and this is the biggest challenge for us. Resources need to be protected, ownership must be clear, and you need to avoid deadlocks & race conditions. But while this is probably the most important and difficult challenge you face when allocating and deallocating in separate threads, it is not directly related to your question, so I'll leave that for another discussion.
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