线程同步一大部分与原子访问(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 );
1 // ThreadSynchronization.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <windows.h> 6 #include <iostream> 7 using namespace std; 8 9 10 11 typedef struct _ITEM_ { 12 ULONG ItemData; 13 SINGLE_LIST_ENTRY ItemEntry; 14 }ITEM,*PITEM; 15 DWORD WINAPI InsertThreadProcedure(LPVOID ParameterData); 16 DWORD WINAPI RemoveThreadProcedure(LPVOID ParameterData); 17 SLIST_HEADER __ListHead; 18 void main() 19 { 20 21 ULONG Count; 22 PSINGLE_LIST_ENTRY ListEntry; 23 24 InitializeSListHead(&__ListHead); 25 26 27 HANDLE ThreadHandle[2] = { 0 }; 28 29 ThreadHandle[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)InsertThreadProcedure, NULL, 0,NULL); 30 ThreadHandle[1] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)RemoveThreadProcedure, NULL, 0,NULL); 31 WaitForMultipleObjects(2, ThreadHandle, TRUE, INFINITE); 32 33 int i = 0; 34 for (i=0;i<2;i++) 35 { 36 CloseHandle(ThreadHandle[i]); 37 ThreadHandle[i] = NULL; 38 } 39 40 ListEntry = __ListHead.Next.Next; 41 while (ListEntry != NULL) 42 { 43 PITEM v1 = CONTAINING_RECORD(ListEntry, ITEM, ItemEntry); 44 45 printf("%d ", v1->ItemData); 46 47 ListEntry = ListEntry->Next; 48 } 49 ListEntry = InterlockedFlushSList(&__ListHead); //全部移除 50 ListEntry = InterlockedPopEntrySList(&__ListHead); 51 if (ListEntry != NULL) 52 { 53 // Error - list is not empty. 54 } 55 } 56 DWORD WINAPI InsertThreadProcedure(LPVOID ParameterData) 57 { 58 int Count = 0; 59 PSINGLE_LIST_ENTRY ListEntry; 60 PITEM Item; 61 for (Count = 1; Count <= 20; Count += 1) 62 { 63 Item = (PITEM)malloc(sizeof(ITEM)); 64 Item->ItemData = Count; 65 ListEntry = InterlockedPushEntrySList(&__ListHead, 66 &Item->ItemEntry); 67 } 68 return 0; 69 } 70 71 DWORD WINAPI RemoveThreadProcedure(LPVOID ParameterData) 72 { 73 int Count = 0; 74 PSINGLE_LIST_ENTRY ListEntry; 75 76 for (Count = 1; Count <= 10; Count += 1) 77 { 78 ListEntry = InterlockedPopEntrySList(&__ListHead); 79 80 if (ListEntry == NULL) 81 { 82 break; 83 } 84 } 85 return 0; 86 }