标签:
使用SignalObjectAndWait即可代替这两句代码。在高性能服务器应用程序中,SignalObjectAndWait可以节省大量的处理时间。
HANDLE g_hSemaphore; volatile LONG g_nThreadIndex = 0; UINT WINAPI HelpThread(LPVOID lpParam) { //这里给每个线程来一个唯一的ID标识 InterlockedExchangeAdd(&g_nThreadIndex, 1); int nCurIndex = g_nThreadIndex; cout<<"进入线程,线程ID="<<nCurIndex<<endl; WaitForSingleObject(g_hSemaphore, INFINITE); cout<<"线程"<<nCurIndex<<"获得信号量资源…………"<<endl; int i = 0; while( i<2 ) { i++; cout<<"线程"<<nCurIndex<<"正在执行任务中…………"<<endl; Sleep(1000); } LONG lPrevCount; //信号量资源使用完毕,释放掉,好让其他等待的线程继续执行 ReleaseSemaphore(g_hSemaphore, 1, &lPrevCount);//把信号量的资源计数+1,返回前一个资源计数的值 cout<<"前一个资源计数为"<<lPrevCount<<"释放信号量资源,线程"<<nCurIndex<<"退出…………"<<endl; return 0; } void SemaphoreTest() { //创建信号量 g_hSemaphore = CreateSemaphore(NULL, 3, 4, NULL); HANDLE hThreads[6]; int i = 0;
<span style="white-space:pre"> </span>//测试多个线程抢占信号量资源 for (; i<6; ++i) { hThreads[i] = (HANDLE)_beginthreadex(NULL, 0, HelpThread, NULL, 0, NULL); } WaitForMultipleObjects(6, hThreads, TRUE, INFINITE); //关闭线程句柄 for ( i=0; i<6; ++i ) CloseHandle(hThreads[i]); cout<<"辅助线程执行完毕…………"<<endl; //任何进程都可以使用OpenSemaphore来得到一个已经存在的信号量句柄,该句柄与当前进程相关联 DWORD dwRet = WaitForSingleObject(g_hSemaphore, 5*1000); switch( dwRet ) { case WAIT_OBJECT_0: cout<<"信号量可用…………"<<endl; break; case WAIT_TIMEOUT: cout<<"等待超时…………"<<endl; break; case WAIT_FAILED: cout<<"WaitForSingleObject调用失败,系统错误码:%u"<<GetLastError()<<endl; break; } //OpenSemaphore() CloseHandle(g_hSemaphore); } UINT __stdcall MutexHelpThread(LPVOID lpParam) { HANDLE hMutex = (HANDLE)lpParam; DWORD dwRet = WaitForSingleObject(hMutex, INFINITE); cout<<"互斥量对象触发"<<endl; return 0; } void MutexTest() { HANDLE hMutex = CreateMutex(NULL, TRUE, NULL); HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, MutexHelpThread, (LPVOID)hMutex, 0, NULL); //释放互斥量,避免两个线程相互等待死锁 ReleaseMutex(hMutex); WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); DWORD dwRet = WaitForSingleObject(hMutex, INFINITE); switch( dwRet ) { case WAIT_OBJECT_0: break; case WAIT_TIMEOUT: break; case WAIT_FAILED: break; } CloseHandle(hMutex); }
Windows核心编程笔记(7)----内核模式下的线程同步
标签:
原文地址:http://blog.csdn.net/mfcing/article/details/44001197