CriticalSection vs Mutex

1. CriticalSection不需要进入内核就可以使用,速度比Mutex快100倍。

2. CriticalSection只能用于同一个进程,而Mutex可以被不同进程使用

 

CriticalSection的伪代码

CRITICAL_SECTION s;

void EnterCriticalSection( CRITICAL_SECTION* s )
{
int spin_count = s.max_count;
while( --spin_count >= 0 )
{
if( InterlockedExchange( &s->Locked, 1 ) == 1 )
{
// we own the lock now
s->OwningThread = GetCurrentThread();
return;
}
}
// lock the mutex and wait for an unlock
WaitForSingleObject( &s->KernelLock, INFINITE );
}
posted @ 2011-02-08 18:48  Fan Zhang  阅读(286)  评论(0编辑  收藏  举报