Provides a light weight exclusive lock that is approximately 2.5 times faster than Monitor. WARNING: This lock should be used in a Using block, and duplicate calls to Lock without releasing will cause a deadlock.
After writing this class I did some review of the methodology. Reviewing this article: http://www.adammil.net/blog/v111_Creating_High-Performance_Locks_and_Lock-free_Code_for_NET_.html Brings up stability issues with the lock. Namely what happens when unhandled exceptions occurs when acquiring and releasing the lock. I have intentionally left out any kind of protection against this as it severly reduces the speed of this code. Therefore do not use this locking method where a Thread.Abort() might be used as a control method.
        public void TestTinyLock_Lock()
        {
            var tl = new TinyLock();
            const int count = 100000000;
            Stopwatch sw = new Stopwatch();
            sw.Start();

            for (int x = 0; x < count; x++)
            {
                using (tl.Lock()) ;
                using (tl.Lock()) ;
                using (tl.Lock()) ;
                using (tl.Lock()) ;
                using (tl.Lock()) ;
                using (tl.Lock()) ;
                using (tl.Lock()) ;
                using (tl.Lock()) ;
                using (tl.Lock()) ;
                using (tl.Lock()) ;
               
            }
            sw.Stop();

            Console.WriteLine((count * 10.0 / sw.Elapsed.TotalSeconds / 1000000));
        }
Ejemplo n.º 2
0
 internal TinyLockRelease(TinyLock tinyLock)
 {
     if ((object)tinyLock == null)
     {
         throw new ArgumentNullException("tinyLock");
     }
     if (tinyLock.m_release.m_tinyLock != null)
     {
         throw new Exception("Object is already locked");
     }
     m_tinyLock = tinyLock;
 }
        public void TestContention()
        {
            m_value = 0;
            m_sync = new TinyLock();
            m_event = new ManualResetEvent(true);

            for (int x = 0; x < 16; x++)
                ThreadPool.QueueUserWorkItem(Adder);

            Thread.Sleep(100);
            m_event.Set();

            while (m_value < 16 * max)
            {
                Console.WriteLine(m_value);
                Thread.Sleep(1000);
            }

            Console.WriteLine(m_value);
        }
 internal TinyLockRelease(TinyLock tinyLock)
 {
     if ((object)tinyLock == null)
         throw new ArgumentNullException("tinyLock");
     if (tinyLock.m_release.m_tinyLock != null)
         throw new Exception("Object is already locked");
     m_tinyLock = tinyLock;
 }