using mutex's with new memory allocation in threads?
Hello,
Multiple threads of the same process will share a common heap on Windows using C++, correct? Therefore should I use a mutex to protect any creations of new objects in my code? Because otherwise, it seems to me that two threads creating memory on the heap at the same time could conflict.
Re: using mutex's with new memory allocation in threads?
yes, multiple threads will share the same heap, but no, you don't need to synchronize allocations ( provided you link with the multithreaded version of the runtime, of course ) because it's already synchronized for you with a spin-counted crititical section ( this means that at least low frequency allocations should not cause a context switch ). If you have performance worries about this, you can create an heap per thread or not use the heap at all ( for example, a stack based allocator ) or use a multithreading optimized memory allocator, like the one coming with the intel multithreading library ...
Last edited by superbonzo; December 20th, 2011 at 08:06 AM.
Reason: typos
Re: using mutex's with new memory allocation in threads?
You may also like to look at thread local storage. Compilers compliant with the new C++ standard can use thread_local. For older compilers you will have to rely on platform specific solutions.
"It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
Richard P. Feynman
Bookmarks