线程同步一大部分与原子访问(atomic access)有关, 所谓原子访问, 指的是一个线程在访问某个资源的同时能够保证没有其他线程会在同一时刻访问同一资源.
Interlocked单向链式栈的操作函数:
InitializeSListHead,创建一个空栈
void WINAPI InitializeSListHead(
__inout PSLIST_HEADER ListHead//链头
);
InterlockedPushEntrySList,在头添加,返回值为之前的第一项,如果之前为空链,则返回NULL。
PSLIST_ENTRY WINAPI InterlockedPushEntrySList(
- __inout PSLIST_HEADER ListHead,//链头
- __inout PSLIST_ENTRY ListEntry//插入项
- );
InterlockedPopEntrySList,在头取出(区别于从尾部取出),返回值就是取的那个项的指针,如果之前为空链,则返回NULL。
PSLIST_ENTRY WINAPI InterlockedPopEntrySList(
__inout PSLIST_HEADER ListHead
);
InterlockedFlushSList,清空栈
PSLIST_ENTRY WINAPI InterlockedFlushSList(
__inout PSLIST_HEADER ListHead
);
QueryDepthSList,返回元素的数量。
USHORT WINAPI QueryDepthSList(
__in PSLIST_HEADER ListHead
);
// ThreadSynchronization.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std; typedef struct _ITEM_ {
ULONG ItemData;
SINGLE_LIST_ENTRY ItemEntry;
}ITEM,*PITEM;
DWORD WINAPI InsertThreadProcedure(LPVOID ParameterData);
DWORD WINAPI RemoveThreadProcedure(LPVOID ParameterData);
SLIST_HEADER __ListHead;
void main()
{ ULONG Count;
PSINGLE_LIST_ENTRY ListEntry; InitializeSListHead(&__ListHead); HANDLE ThreadHandle[] = { }; ThreadHandle[] = CreateThread(NULL, , (LPTHREAD_START_ROUTINE)InsertThreadProcedure, NULL, ,NULL);
ThreadHandle[] = CreateThread(NULL, , (LPTHREAD_START_ROUTINE)RemoveThreadProcedure, NULL, ,NULL);
WaitForMultipleObjects(, ThreadHandle, TRUE, INFINITE); int i = ;
for (i=;i<;i++)
{
CloseHandle(ThreadHandle[i]);
ThreadHandle[i] = NULL;
} ListEntry = __ListHead.Next.Next;
while (ListEntry != NULL)
{
PITEM v1 = CONTAINING_RECORD(ListEntry, ITEM, ItemEntry); printf("%d ", v1->ItemData); ListEntry = ListEntry->Next;
}
ListEntry = InterlockedFlushSList(&__ListHead); //全部移除
ListEntry = InterlockedPopEntrySList(&__ListHead);
if (ListEntry != NULL)
{
// Error - list is not empty.
}
}
DWORD WINAPI InsertThreadProcedure(LPVOID ParameterData)
{
int Count = ;
PSINGLE_LIST_ENTRY ListEntry;
PITEM Item;
for (Count = ; Count <= ; Count += )
{
Item = (PITEM)malloc(sizeof(ITEM));
Item->ItemData = Count;
ListEntry = InterlockedPushEntrySList(&__ListHead,
&Item->ItemEntry);
}
return ;
} DWORD WINAPI RemoveThreadProcedure(LPVOID ParameterData)
{
int Count = ;
PSINGLE_LIST_ENTRY ListEntry; for (Count = ; Count <= ; Count += )
{
ListEntry = InterlockedPopEntrySList(&__ListHead); if (ListEntry == NULL)
{
break;
}
}
return ;
}
ThreadSynchronization.cpp