[Algorithms] RE: simple threading control
Brought to you by:
vexxed72
From: Jeff R. <je...@ra...> - 2003-12-12 03:09:59
|
One thing that you are missing is tracking which thread already has the lock, so that further locks on that same thread always succeed. Otherwise, you'll deadlock against your own thread. ->Jeff RAD Game Tools > Message: 12 > Date: Wed, 10 Dec 2003 11:31:46 -0800 > To: gda...@li... > From: Charles Bloom <cb...@cb...> > Subject: [Algorithms] simple threading control > Reply-To: gda...@li... > > > Anyone know of robust, simple, tested thread control code? I need to > thread-safe singleton initialization and simple "critical sections" using > only the lowest-level ops (interlocked compare and interlocked > increment). This is what we've come up with, but thread stuff is scary, so > I'd love to get something that's not home brew - > > void SimpleSemaphore_Lock(volatile LONG * ptr) > { > // 0 is unlocked, 1 is locked > while( InterlockedCompareExchange(ptr,1,0) == 1 ) > { > Sleep(0); > } > // *ptr should now be 1 > } > > void SimpleSemaphore_Unlock(volatile LONG * ptr) > { > // *ptr should now be 1 > InterlockedDecrement(ptr); > // *ptr should now be 0 > // if there was a higher priority thread stalled on us, wake it up ! > } > > template <typename T> > T * GetSafeSingleton() > { > static T * ptr = NULL; > static volatile LONG counter = 0; > if ( InterlockedIncrement(&counter) == 1 ) > { > static T instance; > ptr = &instance; > } > while( ptr == NULL ) > { > // this can be hit if we get a thread-switch between the > time of hitting the InterlockedIncrement > // and the time of doing the assignment to ptr > Sleep(0); > } > return ptr; > } > > > ---------------------------------------------------- > Charles Bloom email "cb" http://www.cbloom.com |