Windows API实现的栈及使用(支持线程安全,以原子方式操作)

来源:互联网 发布:权志龙用什么软件直播 编辑:程序博客网 时间:2024/06/05 18:12

InitializeSListHead:创建一个空栈。

InterlockedPushEntrySList:在栈顶添加一个元素。

InterlockedPopEntrySList:移除位于栈顶的元素并将它返回。

InterlockedFlushSList:清空栈。

QueryDepthSList:返回栈中元素的数量。


使用方法:

#include <windows.h>#include <malloc.h>// Structure to be used for a list item. Typically, the first member // is of type SINGLE_LIST_ENTRY. Additional members are used for data. // Here, the data is simply a signature for testing purposes. typedef struct _PROGRAM_ITEM {    SINGLE_LIST_ENTRY ItemEntry;    ULONG Signature; } PROGRAM_ITEM, *PPROGRAM_ITEM;void main( ){    ULONG Count;    PSINGLE_LIST_ENTRY FirstEntry, ListEntry;    SLIST_HEADER ListHead;    PPROGRAM_ITEM ProgramItem;    // Initialize the list header.    InitializeSListHead(&ListHead);    // Insert 10 items into the list.    for( Count = 1; Count <= 10; Count += 1 )    {        ProgramItem = (PPROGRAM_ITEM)malloc(sizeof(*ProgramItem));        ProgramItem->Signature = Count;        FirstEntry = InterlockedPushEntrySList(&ListHead,                        &ProgramItem->ItemEntry);     }    // Remove 10 items from the list.    for( Count = 10; Count >= 1; Count -= 1 )    {        ListEntry = InterlockedPopEntrySList(&ListHead);    }    // Flush the list and verify that the items are gone.    ListEntry = InterlockedFlushSList(&ListHead);    FirstEntry = InterlockedPopEntrySList(&ListHead);    if (FirstEntry != NULL)    {        // Error - list is not empty.    }}

0 0