1

当我在前面的代码示例中调用 HeapCreate 函数时,我使用了 HEAP_NO_SERIALIZE 标志,因为示例代码的其余部分不是多线程安全的。

Jeffrey Richter 在他的书(Windows via C/C++)中写了这句话,
但这很奇怪。
如果代码不是多线程安全的,他就不必使用该标志。
它是一个错误吗?还是我误解了什么?

4

2 回答 2

1

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.

于 2010-08-25T07:54:21.183 回答
0

默认情况下,Windows 堆执行附加逻辑以确保没有两个线程同时从堆中分配内存。这是如何完成的仍然是一个秘密,但它可能会是这样的:

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

但是,如果您的应用程序未使用多线程,则关键部分可能具有不可忽略的开销。要消除这种开销,您必须传递标志 HEAP_NO_SERIALIZE,这将消除对关键部分的调用,从而使应用程序稍微快一些。

于 2010-08-25T07:55:24.750 回答