做了个小程序,用来验证Interlocked的效果:
上图分别是注释掉“标记1”和“标记2”后的截图,和取消注释后的截图,下面是代码:
#include <windows.h> #include <stdio.h> #include <float.h> #include <process.h> #include <conio.h> #include <iostream> #include <tchar.h> using namespace std; LONG g = 0, flag = 0, T = 1, F = 0; void threadfun1(void *pNull); void threadfun2(void *pNull); int main() { TCHAR szBuf[10240] = {0};// = TEXT("Thread Interlocked Experiment BEGIN!!!\n"); HANDLE harr[2]; harr[0] = (HANDLE)_beginthread(threadfun1, 0, szBuf); harr[1] = (HANDLE)_beginthread(threadfun2, 0, szBuf); // 如果不等两个线程结束,则极有可能主函数结束了,而那两个线程没结束!; // 也就是说,屏幕上将无任何输出!; WaitForMultipleObjects(2, harr, TRUE, INFINITE); _tprintf(szBuf); printf("%d\n", g); getch(); return 0; } void threadfun1(void *pNull) { // 标记1 while (InterlockedExchange(&flag, T) == T) ; g++; int i, len, j; TCHAR *pStr = (TCHAR*)pNull; for (i = 0; i < 10; ++i) { for (j = 0; j < 10; ++j) { len = lstrlen(pStr); pStr[len++] = '1'; pStr[len] = 0; } len = lstrlen(pStr); pStr[len++] = '\n'; pStr[len] = 0; Sleep(10); // 这样使实验的效果更明显; } InterlockedExchange(&flag, F); } void threadfun2(void *pNull) { // 标记2 while(InterlockedExchange(&flag, T) == T) ; g++; int i, len, j; TCHAR *pStr = (TCHAR*)pNull; for (i = 0; i < 10; ++i) { for (j = 0; j < 10; ++j) { len = lstrlen(pStr); pStr[len++] = '2'; pStr[len] = 0; } len = lstrlen(pStr); pStr[len++] = '\n'; pStr[len] = 0; Sleep(10); } InterlockedExchange(&flag, F); }