我写了一个小程序来比较
Windows中Critical Section vs Mutex的性能.
在我跑的测试中,获得关键部分似乎更慢:O任何人都可以解释为什么两件事花费的时间差不多,以及内部发生了什么.
这是我使用的计时器 – http://cplus.about.com/od/howtodothingsi2/a/timing.htm
#include "stdafx.h" #include<iostream> #include<vector> #include "h_timer.h" #include<WinBase.h> #include<Windows.h> #include<stdio.h> #define MAX_THREADS 2000 //Comment and Uncomment this to enable/disable critialSection / Mutex #define CRIT 1 using namespace std; HANDLE Mutex; CRITICAL_SECTION critSection; DWORD WINAPI Contention( LPVOID ); int main( void ) { HANDLE Thread[MAX_THREADS]; DWORD ThreadID; int i; #ifdef CRIT //create a critical section InitializeCriticalSection(&critSection); #else // Create a mutex with no initial owner Mutex = CreateMutex( NULL,FALSE,NULL); #endif // Create worker threads CStopWatch timer,tempTimer; timer.startTimer(); for( i=0; i < MAX_THREADS; i++ ) { Thread[i] = CreateThread( NULL,(LPTHREAD_START_ROUTINE)Contention,NULL,&ThreadID); } WaitForMultipleObjects(MAX_THREADS,Thread,TRUE,INFINITE); timer.stopTimer(); cout<<endl<<"Elapsed Time:"<<timer.getelapsedtime(); cin.get(); // Close thread and mutex handles for( i=0; i < MAX_THREADS; i++ ) CloseHandle(Thread[i]); CloseHandle(Mutex); return 0; } DWORD WINAPI Contention( LPVOID lpParam ) { #ifdef CRIT EnterCriticalSection(&critSection); //printf("ThreadId: %d\n",GetCurrentThreadId()); //printf("Let's try Again. %d\n\n",GetCurrentThreadId()); LeaveCriticalSection(&critSection); #else // lpParam not used in this example UNREFERENCED_ParaMETER(lpParam); DWORD dwCount=0,dwWaitResult; // Request ownership of mutex. dwWaitResult = WaitForSingleObject( ghMutex,// handle to mutex INFINITE); // no time-out interval dwCount++; ReleaseMutex(ghMutex); #endif return TRUE; }
对于2000线程,在四核HPZ210上,两者都需要大约1.5秒.
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。