Example #1
0
        private static int Run(int concurrencyLevel, int x, int y, int z)
        {
            object _lock = new object();

            int count_locks = 0;
            var _locks      = new lockItem[concurrencyLevel];

            for (int i = 0; i < concurrencyLevel; i++)
            {
                _locks[i] = new lockItem();
            }

            Action <Guid> fnc = (g) =>
            {
                int lockNo = (g.GetHashCode() & 0x7fffffff) % concurrencyLevel;
                var item   = _locks[lockNo];

                if (item.Count > 1)
                {
                    count_locks++;
                }

                lock (_lock)
                    item.Count++;

                Thread.Sleep(y);

                lock (_lock)
                    item.Count--;
            };


            for (int i = 0; i < x; i++)
            {
                Task.Factory.StartNew(() => fnc(Guid.NewGuid()));
                Thread.Sleep(z);
                if (count_locks > 0)
                {
                    return(i);
                }
            }

            while (count_locks > 0)
            {
                Task.Yield();
            }

            return(0);
        }
Example #2
0
        public void Concurrency_Keys_UnitTest1()
        {
            int concurrencyLevel = 1000;

            var _locks = new lockItem[concurrencyLevel];

            for (int i = 0; i < concurrencyLevel; i++)
            {
                _locks[i] = new lockItem();
            }

            for (int i = 0; i < concurrencyLevel; i++)
            {
                var key = Guid.NewGuid();

                int hashcode = key.GetHashCode();                               // and logic 0x7fffffff -> remove sign and result is positive
                int lockNo   = (hashcode & 0x7fffffff) % concurrencyLevel;      // modulo -> find an integer less than array length
                Assert.IsTrue(lockNo >= 0 && lockNo < concurrencyLevel);        //

                var item = _locks[lockNo];

                item.Count++;
            }

            int count_unuseds = 0;
            int count_locks   = 0;
            int max_locks     = 0;

            for (int lockNo = 0; lockNo < concurrencyLevel; lockNo++)
            {
                var item = _locks[lockNo];
                max_locks = Math.Max(max_locks, item.Count);
                if (item.Count == 0)
                {
                    count_unuseds++;
                }
                else if (item.Count > 1)
                {
                    count_locks++;
                }
            }
        }