一种临界区的实现

来源:互联网 发布:淘宝买白酒靠谱吗 编辑:程序博客网 时间:2024/05/22 17:15
利用
InterlockedCompareExchange和NtDelayExecution配合 ,特点 轻量,但耗费一些效率在NtDelayExecution上
list<CString> g_listQueue;volatile long g_lock=0; typedef NTSTATUS (NTAPI *PFN_NtDelayExecution)( IN BOOLEAN Alertable,  IN PLARGE_INTEGER Interval );void mini_delay(){static HMODULE hdll =::GetModuleHandle(L"ntdll.dll");if(hdll){static PFN_NtDelayExecution fn = (PFN_NtDelayExecution)GetProcAddress(hdll, "NtDelayExecution");if(fn){LARGE_INTEGER lar = {};lar.QuadPart = -1;fn(TRUE, &lar);}}}void MyEnterCriticalSection(volatile long* pllock){redo:if(InterlockedCompareExchange(&g_lock, 1, 0) == 0){return;}else{mini_delay();goto redo;}}void MyLeaveCriticalSection(volatile long* pllock){(*pllock) = 0;}DWORD WINAPI proc1(LPVOID lpp){while(1){int tr=0;::Sleep(tr=(rand()%10));CString str;str.Format(L"---->%d\n",tr); MyEnterCriticalSection(&g_lock);{g_listQueue.push_back(str);}MyLeaveCriticalSection(&g_lock);}return 0;}DWORD WINAPI proc2(LPVOID lpp){while(1){if (g_listQueue.size()>0){CString sr;MyEnterCriticalSection(&g_lock);{sr=*(g_listQueue.begin());g_listQueue.pop_front();}MyLeaveCriticalSection(&g_lock);printf("%S",(LPCWSTR)sr);}}return 0;}int _tmain(int argc, _TCHAR* argv[]){CreateThread(0,0,proc1,0,0,0);CreateThread(0,0,proc2,0,0,0);while(1){mini_delay();//::Sleep(1);}
}

0 1
原创粉丝点击