HEAP_NO_SERIALIZE flag

1.8k views Asked by At

When I called the HeapCreate function in the preceding code sample, I used the HEAP_NO_SERIALIZE flag because the remainder of the sample code is not multithread-safe.

Jeffrey Richter wrote the sentence in his book(Windows via C/C++)
But it's weird.
If the codes are not multithread-safe he didn't have to use the flag.
Is it a bug? Or am I misunderstanding something?

2

There are 2 answers

0
DarthCoder On

With the HEAP_NO_SERIALIZE flag you just tell the Heap that it will never be accessed by different threads, therefore there is no need for thread-safeness at all.

If you do not specify this flag, the heap will internally acquire a lock at every call to the HeapXXX Functions, so you would have the overhead of this although you are accessing the heap from only one thread.

EDIT: In this sample, as it is not thread-safe at all ( and therefore I assume does not employ threading in any way ), it makes perfect sense to inform the heap, that it mustn't be threadsafe.

2
Patrick On

By default the Windows heap performs additional logic to make sure that no two threads allocate memory from the heap at the same time. How this is exactly done remains a secret, but it will probably be something like this:

EnterCriticalSection (&cs);
... // Perform logic to allocate memory, set list pointers, ...
LeaveCriticalSection (&cs);

However, if your application is not using multithreading, the critical sections may have a non-neglectable overhead. To remove this overhead, you have to pass the flag HEAP_NO_SERIALIZE, which will remove the calls to the critical section, resulting in a slightly faster application.