using mutex's with new memory allocation in threads?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: using mutex's with new memory allocation in threads?

  1. #1
    Join Date
    Mar 2009
    Posts
    166

    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.

    Regards,
    Ellay K.

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,888

    Re: using mutex's with new memory allocation in threads?

    I've never noticed this to be a problem in practice.

  3. #3
    Join Date
    Oct 2008
    Posts
    1,105

    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

  4. #4
    Join Date
    May 2009
    Posts
    2,413

    Re: using mutex's with new memory allocation in threads?

    Quote Originally Posted by superbonzo View Post
    or use a multithreading optimized memory allocator, like the one coming with the intel multithreading library ...
    http://threadingbuildingblocks.org/

  5. #5
    Join Date
    Jul 2002
    Location
    Portsmouth. United Kingdom
    Posts
    2,699

    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center