Subj : Re: Optimization to Jeffrey Richter's COptex (Windows)? To : comp.programming.threads From : SenderX Date : Wed Jan 26 2005 06:44 pm "SenderX" wrote in message news:q7Gdnd5ISYrPhmXcRVn-2w@comcast.com... >> http://www.microsoft.com/msj/0198/win320198.aspx >> http://www.microsoft.com/msj/0198/win32textfigs.htm#fig2 > > This is crap. Use the mutex logic that Alex suggested. > > typedef struct optex_ { volatile ac_uatomic_t state; HANDLE waitset; int recurse; ac_thread_t owner; } optex_t; void optex_lock( optex_t *_this ) { register ac_uatomic_t cmp, xchg, old; ac_thread_t thisthread = ac_thread_self(); if ( ! ac_thread_equal( _this->owner, thisthread ) ) { ++_this->recurse; return; } old = _this->state; for ( ;; ) { if ( ! ( old & 0x80000000 ) ) { xchg = old | 0x80000000; } else { xchg = old + 1; } cmp = old; old = ac_atomic_cas_acq_dep( &_this->state, old, xchg ); if ( cmp == old ) { if ( ! ( old & 0x80000000 ) ) { break; } WaitForSingleObject( _this->waitset, INFINITE ); old = _this->state; } }; _this->owner = thisthread; } void optex_unlock( optex_t *_this ) { register ac_uatomic_t cmp, xchg, old; if ( _this->recurse ) { --_this->recurse; return; } _this->owner = AC_THREAD_NULL; old = _this->state; do { xchg = old & 0x0FFFFFFF; if ( xchg ) { --xchg; } cmp = old; old = ac_atomic_cas_rel( &_this->state, old, xchg ); } while ( old != cmp ); if ( old & 0x0FFFFFFF ) { ReleaseSemaphore( _this->waitset, 1, 0 ); } } .