Equalizer 1.0

spinLock.h

00001 
00002 /* Copyright (c) 2010, Stefan Eilemann <eile@equalizergraphics.com> 
00003  *
00004  * This library is free software; you can redistribute it and/or modify it under
00005  * the terms of the GNU Lesser General Public License version 2.1 as published
00006  * by the Free Software Foundation.
00007  *  
00008  * This library is distributed in the hope that it will be useful, but WITHOUT
00009  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
00010  * FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
00011  * details.
00012  * 
00013  * You should have received a copy of the GNU Lesser General Public License
00014  * along with this library; if not, write to the Free Software Foundation, Inc.,
00015  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
00016  */
00017 
00018 #ifndef COBASE_SPINLOCK_H
00019 #define COBASE_SPINLOCK_H
00020 
00021 #include <co/base/atomic.h>         // member
00022 #include <co/base/compareAndSwap.h> // used in inline method
00023 #include <co/base/nonCopyable.h>    // base class
00024 #include <co/base/thread.h>         // used in inline method
00025 
00026 namespace co
00027 {
00028 namespace base
00029 {
00037     class SpinLock : public NonCopyable
00038     {
00039     public:
00041         SpinLock() : _set( 0 ) {}
00042 
00044         ~SpinLock() { _set = 0; }
00045 
00047         void set()
00048             {
00049                 while( true )
00050                 {
00051                     for( unsigned i=0; i < 100; ++i )
00052                     {
00053                         if( compareAndSwap( &_set, 0, 1 ))
00054                             return;
00055                         Thread::yield();
00056                     }
00057                 }
00058             }
00059 
00061         void unset() { _set = 0; memoryBarrier(); }
00062 
00072         bool trySet()
00073             {
00074                 if( compareAndSwap( &_set, 0, 1 ))
00075                     return true;
00076                 return false;
00077             }
00078 
00086         bool isSet() { memoryBarrier(); return ( _set == 1 ); }
00087 
00088     private:
00089         long _set;
00090     };
00091 }
00092 
00093 }
00094 #endif //COBASE_SPINLOCK_H
Generated on Sun May 8 2011 19:11:07 for Equalizer 1.0 by  doxygen 1.7.3