Author: Scott Gasch
Date: 11:51:30 11/19/04
Go up one level in this thread
On November 18, 2004 at 07:36:58, Daniel Shawul wrote:
>i have made a wrapper class for the lock/unlock operations
>that i do at a struct SPLIT.
>SPLIT
>{
> //HANDLE lock;
> CRITICAL_SECTION cs;
> other data...
>}
> At codeguru site i read that critical sections are faster than
>mutexes.But for me they are *very very slower*. I am sure i am doing something
>wrong but don't know what?
>Another question is how profitable is using methods like InterLockedExchange,
>i mean going low level, for SMP chess engines?
>
>SPLIT::SPLIT()
>{
> //lock = CreateMutex(NULL,0,NULL);
> InitializeCriticalSection(& cs);
>}
>SPLIT::~SPLIT()
>{
> //CloseHandle();
> DeleteCriticalSection(& cs);
>}
>SPLIT::Lock()
>{
> //WaitForSingleObject(lock,INFINITE);
> EnterCriticalSection(& cs);
>}
>SPLIT::UnLock()
>{
> //ReleaseMutex(lock);
> LeaveCriticalSection(& cs);
>}
>
>best
>daniel
Let me make two suggestions:
1. Ditch the critical sections and make spin locks. They are simple to do: have
a thread spin doing an InterlockedCompareExchange (or assembly language lock
cmpxchg) on a global.
2. Let's back up a second and do some definitions: the difference between a spin
lock and a normal CRITICAL_SECTION is what happens when a thread goes to acquire
the lock but the lock is held by another thread. With a CRITICAL_SECTION the
thread trying to acquire is suspended and put on a wait queue -- it gives up the
rest of its CPU time for that quantum. When the lock becomes available the
waiting thread will be woken up to run again. With a spin lock the waiter keeps
running and spinning in a loop trying to acquire the lock over and over again.
The advantage is that if you are on an MP machine and if the lock is not
normally held for a long time then the guy holding the lock it probably running
in the other CPU and will probably release the lock after you loop a few
thousand times. With a normal CRITICAL_SECTION you lose your quantum, and pay
two thread context switches.
Now, there is a way in Win32 to create a critical section with a spin lock on
it. Read the MSDN page for InitialzeCriticalSectionEx. With one of these, when
a thread goes to acquire a CS that is locked, it first spins in a spin loop N
times (N is provided by you at CS init time). If after N loops spinning it
still doesn't have the lock then it goes into a wait state.
Scott
This page took 0 seconds to execute
Last modified: Thu, 15 Apr 21 08:11:13 -0700
Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.