views:

19

answers:

2

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?

+1  A: 

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.

DarthCoder
A: 

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.

Patrick
"is not multithread-safe" means "not using multithreading"?
Benjamin
I think you(and DarthCoder) assumed both of words are equal. Didn't you? But it looks different to me.
Benjamin
Thread-safe means that your code is allowed to be used in multiple threads at the same time. Code that is not-thread-safe is bound to crash sooner or later in a multithreaded application. Multithreading itself means that the application is using multiple threads. You can use thread-safe code in a single-threaded application. But it's not advised to use non-thread-safe-code in a multi-threaded application.
Patrick