protected override int MapPriority(TPriority prior)
        {
            TurboContract.Ensures(TurboContract.Result <int>() >= 0);
            TurboContract.Ensures(TurboContract.Result <int>() < this.PriorityLevelsCount);

            throw new NotImplementedException();
        }
        /// <summary>
        /// Захватить лучший элемент из доступных
        /// </summary>
        /// <param name="element">Захваченный элемент</param>
        /// <returns>Удалось ли захватить</returns>
        private bool TryTakeBest(out PoolElementWrapper <T> element)
        {
            TurboContract.Ensures((TurboContract.Result <bool>() == false && TurboContract.ValueAtReturn(out element) == null) ||
                                  (TurboContract.Result <bool>() == true && TurboContract.ValueAtReturn(out element) != null && TurboContract.ValueAtReturn(out element).IsBusy));

            PoolElementWrapper <T> b1, b2, b3;
            PoolElementWrapper <T> earlyStopResult = FindBest3WithStopping(out b1, out b2, out b3);

            if (earlyStopResult != null)
            {
                TurboContract.Assert(earlyStopResult.IsBusy, conditionString: "earlyStopResult.IsBusy");
                element = earlyStopResult;
                return(true);
            }
            if (b1 != null && b1.TryMakeBusyAtomic() && !b1.IsRemoved)
            {
                element = b1;
                return(true);
            }
            if (b2 != null && b2.TryMakeBusyAtomic() && !b2.IsRemoved)
            {
                element = b2;
                return(true);
            }
            if (b3 != null && b3.TryMakeBusyAtomic() && !b3.IsRemoved)
            {
                element = b3;
                return(true);
            }

            element = null;
            return(false);
        }
Ejemplo n.º 3
0
        /// <summary>Code contracts</summary>
        public bool TryGetAssociation(T key, out LifetimeBase val)
        {
            TurboContract.Ensures((TurboContract.Result <bool>() == true && TurboContract.ValueAtReturn <LifetimeBase>(out val) != null) ||
                                  (TurboContract.Result <bool>() == false && TurboContract.ValueAtReturn <LifetimeBase>(out val) == null));

            throw new NotImplementedException();
        }
Ejemplo n.º 4
0
        public bool TryResolve(T key, out object val)
        {
            TurboContract.Requires(key != null, conditionString: "key != null");
            TurboContract.Ensures(TurboContract.Result <bool>() == true || (TurboContract.Result <bool>() == false && TurboContract.ValueAtReturn <object>(out val) == null));

            throw new NotImplementedException();
        }
Ejemplo n.º 5
0
        public object CreateInstance(IInjectionResolver resolver)
        {
            TurboContract.Requires(resolver != null, conditionString: "resolver != null");
            TurboContract.Ensures(TurboContract.Result <object>() != null);

            throw new NotImplementedException();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Выборка элемента из головы (может вызываться из любого потока)
        /// </summary>
        /// <param name="item">Выбранный элемент</param>
        /// <returns>Удалось ли сделать выборку</returns>
        public bool TrySteal(out ThreadPoolWorkItem item)
        {
            TurboContract.Ensures(TurboContract.Result <bool>() == false || TurboContract.ValueAtReturn(out item) != null);

            if (HasElements(_head, _tail))
            {
                lock (_syncObj)
                {
                    int head = _head;
                    if (HasElements(head, _tail))
                    {
                        item = Interlocked.Exchange(ref _data[head % QueueSize], null);
                        if (item != null)
                        {
                            //RemoveElementFromHead();
                            _head = head + 1;
                            return(true);
                        }
                    }
                }
            }

            item = null;
            return(false);
        }
        /// <summary>
        /// Добавить локальную оередь в массив
        /// </summary>
        /// <param name="localQueue">Локальная очередь потока</param>
        public void AddLocalQueue(ThreadPoolLocalQueue localQueue)
        {
            TurboContract.Requires(localQueue != null, conditionString: "localQueue != null");
            TurboContract.Ensures(_localQueues.Contains(localQueue));

            TurboContract.Assert(!_isDisposed, conditionString: "!_isDisposed");

            lock (_syncObj)
            {
                var arrayCopy = _localQueues;
                TurboContract.Assert(arrayCopy != null, conditionString: "arrayCopy != null");

                for (int i = 0; i < arrayCopy.Length; i++)
                {
                    TurboContract.Assert(Volatile.Read(ref arrayCopy[i]) != localQueue, conditionString: "Volatile.Read(ref arrayCopy[i]) != localQueue");

                    if (Volatile.Read(ref arrayCopy[i]) == null)
                    {
                        Volatile.Write(ref arrayCopy[i], localQueue);
                        return;
                    }
                }

                int oldLength = arrayCopy.Length;
                Array.Resize(ref arrayCopy, oldLength + 4);

                Volatile.Write(ref arrayCopy[oldLength], localQueue);
                _localQueues = arrayCopy;
            }
        }
        // =====================


        /// <summary>
        /// Попробовать выполнить похищение элемента из соседних локальных очередей
        /// </summary>
        /// <param name="localQueue">Локальная очередь текущего потока</param>
        /// <param name="otherLocalQueues">Разреженный массив локальных очередей других потоков</param>
        /// <param name="item">Выбранный элемент</param>
        /// <returns>Удалось ли сделать выборку</returns>
        private bool TryTakeFromOtherLocalQueues(ThreadPoolLocalQueue localQueue, ThreadPoolLocalQueue[] otherLocalQueues, out ThreadPoolWorkItem item)
        {
            TurboContract.Requires(otherLocalQueues != null, conditionString: "otherLocalQueues != null");
            TurboContract.Ensures(TurboContract.Result <bool>() == false || TurboContract.ValueAtReturn(out item) != null);


            bool result = false;

            item = null;

            try { }
            finally
            {
                int length = otherLocalQueues.Length;
                int index  = Interlocked.Increment(ref _stealIndex) & int.MaxValue;
                for (int i = 0; i < length; i++, index++)
                {
                    var otherQueue = Volatile.Read(ref otherLocalQueues[index % length]);
                    if (otherQueue != null && otherQueue != localQueue && otherQueue.TrySteal(out item))
                    {
                        result = true;
                        break;
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Produces full description for the Exception (almost equivalent to ToString results)
        /// </summary>
        /// <param name="ex">Source exception</param>
        /// <returns>Full description for the exception</returns>
        public static string GetFullDescription(this Exception ex)
        {
            TurboContract.Requires(ex != null, conditionString: "ex != null");
            TurboContract.Ensures(TurboContract.Result <string>() != null);

            if (ex == null)
            {
                throw new ArgumentNullException(nameof(ex));
            }

            StringBuilder builder = new StringBuilder(1000);

            builder.Append(ex.GetType().Name).Append(": ").Append(ex.Message).AppendLine();
            builder.Append("Source: ").Append(ex.Source).AppendLine();
            builder.Append("StackTrace: ").Append(ex.StackTrace).AppendLine();

            Exception cur = ex.InnerException;

            while (cur != null)
            {
                builder.Append("--> ").Append(cur.GetType().Name).Append(": ").Append(cur.Message).AppendLine();
                builder.Append("    Source: ").Append(cur.Source).AppendLine();
                builder.Append("    StackTrace: ").Append(cur.StackTrace).AppendLine();
                cur = cur.InnerException;
            }

            return(builder.ToString());
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Creates TransformedReadOnlyListWrapper from the current list
        /// </summary>
        /// <typeparam name="TOut">Type of the elements of the newly created TransformedReadOnlyListWrapper</typeparam>
        /// <param name="selector">Element conversion delegate</param>
        /// <returns>Created TransformedReadOnlyListWrapper</returns>
        public TransformedReadOnlyListWrapper <T, TOut> AsTransformedReadOnlyList <TOut>(Func <T, TOut> selector)
        {
            TurboContract.Requires(selector != null, conditionString: "selector != null");
            TurboContract.Ensures(TurboContract.Result <TransformedReadOnlyListWrapper <T, TOut> >() != null);

            return(new TransformedReadOnlyListWrapper <T, TOut>(_list, selector));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Wraps existed Set instance with ReadOnlyHashSet
        /// </summary>
        /// <typeparam name="T">The type of elements in the set</typeparam>
        /// <param name="set">Source HashSet</param>
        /// <returns>ReadOnlyHashSet that wraps specified HashSet instance</returns>
        public static ReadOnlyHashSet <T> AsReadOnlyHashSet <T>(this HashSet <T> set)
        {
            TurboContract.Requires(set != null, conditionString: "set != null");
            TurboContract.Ensures(TurboContract.Result <ReadOnlyHashSet <T> >() != null);

            return(new ReadOnlyHashSet <T>(set));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Wraps existed ICollection with ReadOnlyCollectionWrapper
        /// </summary>
        /// <typeparam name="T">The type of elements in the collection</typeparam>
        /// <param name="col">Source collection</param>
        /// <returns>ReadOnlyCollectionWrapper that wraps specified ICollection instance</returns>
        public static ReadOnlyCollectionWrapper <T> AsReadOnlyCollectionWrapper <T>(this ICollection <T> col)
        {
            TurboContract.Requires(col != null, conditionString: "col != null");
            TurboContract.Ensures(TurboContract.Result <ReadOnlyCollectionWrapper <T> >() != null);

            return(new ReadOnlyCollectionWrapper <T>(col));
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Wraps existed IList collection with ReadOnlyListWrapper
        /// </summary>
        /// <typeparam name="T">The type of elements in the list</typeparam>
        /// <param name="list">Source list of items</param>
        /// <returns>ReadOnlyListWrapper that wraps specified IList instance</returns>
        public static ReadOnlyListWrapper <T> AsReadOnlyListWrapper <T>(this IList <T> list)
        {
            TurboContract.Requires(list != null, conditionString: "list != null");
            TurboContract.Ensures(TurboContract.Result <ReadOnlyListWrapper <T> >() != null);

            return(new ReadOnlyListWrapper <T>(list));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Wraps existed Dictionary instance with ReadOnlyDictionary
        /// </summary>
        /// <typeparam name="TKey">The type of keys in the dictionary</typeparam>
        /// <typeparam name="TValue">The type of values in the dictionary</typeparam>
        /// <param name="dict">Source dictionary</param>
        /// <returns>ReadOnlyDictionary that wraps specified Dictionary instance</returns>
        public static ReadOnlyDictionary <TKey, TValue> AsReadOnlyDictionary <TKey, TValue>(this Dictionary <TKey, TValue> dict)
        {
            TurboContract.Requires(dict != null, conditionString: "dict != null");
            TurboContract.Ensures(TurboContract.Result <ReadOnlyDictionary <TKey, TValue> >() != null);

            return(new ReadOnlyDictionary <TKey, TValue>(dict));
        }
Ejemplo n.º 15
0
        public override object GetInstance(IInjectionResolver resolver)
        {
            TurboContract.Requires(resolver != null, conditionString: "resolver != null");
            TurboContract.Ensures((TurboContract.Result <object>() != null && TurboContract.Result <object>().GetType() == this.OutputType) ||
                                  (TurboContract.Result <object>() == null && this.OutputType.IsAssignableFromNull()));

            throw new NotImplementedException();
        }
        protected override bool TryGetAssociationInner(T key, out LifetimeBase val)
        {
            TurboContract.Requires(key != null, conditionString: "key != null");
            TurboContract.Ensures((TurboContract.Result <bool>() == true && TurboContract.ValueAtReturn <LifetimeBase>(out val) != null) ||
                                  (TurboContract.Result <bool>() == false && TurboContract.ValueAtReturn <LifetimeBase>(out val) == null));

            throw new NotImplementedException();
        }
        protected override LifetimeBase ProduceResolveInfo(T key, Type objType, Lifetime.Factories.LifetimeFactory val)
        {
            TurboContract.Requires(key != null, conditionString: "key != null");
            TurboContract.Requires(objType != null, conditionString: "objType != null");
            TurboContract.Requires(val != null, conditionString: "val != null");
            TurboContract.Ensures(TurboContract.Result <LifetimeBase>() != null);

            throw new NotImplementedException();
        }
        /// <summary>
        /// Copies the priority queue elements to a new array
        /// </summary>
        /// <returns>A new array containing elements copied from the queue</returns>
        public TElem[] ToArray()
        {
            TurboContract.Ensures(TurboContract.Result <TElem[]>() != null);
            TurboContract.Ensures(TurboContract.Result <TElem[]>().Length == this.Count);

            TElem[] array = new TElem[this._count];
            this.CopyTo(array, 0);
            return(array);
        }
        /// <summary>
        /// Adds an object to the priority queue at specified priority level
        /// </summary>
        /// <param name="item">The item to add to the queue</param>
        /// <param name="priority">Priority marker</param>
        public void Enqueue(TElem item, TPriority priority)
        {
            TurboContract.Ensures(this.Count == TurboContract.OldValue(this.Count) + 1);

            int map = MapPriority(priority);

            _innerQueue[map].Enqueue(item);
            _count++;
        }
        public override LifetimeBase Create(Type objType, IInjectionResolver injection, object extInfo)
        {
            TurboContract.Requires(objType != null, conditionString: "objType != null");
            TurboContract.Requires(injection != null, conditionString: "injection != null");
            TurboContract.Ensures(TurboContract.Result <LifetimeBase>() != null);
            TurboContract.Ensures(TurboContract.Result <LifetimeBase>().OutputType == objType);

            throw new NotImplementedException();
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Забрать элемент из очереди
        /// </summary>
        /// <returns>Полученный элемент</returns>
        public ThreadPoolWorkItem Take()
        {
            TurboContract.Ensures(TurboContract.Result <ThreadPoolWorkItem>() != null);

            ThreadPoolWorkItem result = null;
            bool success = TryTake(out result, Timeout.Infinite, new CancellationToken(), true);

            TurboContract.Assert(success, "Element was not taken from ThreadPoolGlobalQueue due to unknown reason");
            return(result);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Sets the capacity to the actual number of elements in the list, if that number is less than 90 percent of current capacity
        /// </summary>
        public void TrimExcess()
        {
            TurboContract.Ensures(this.Count == TurboContract.OldValue(this.Count));

            int minSize = (int)((double)_elemArray.Length * ShrinkRate);

            if (_size < minSize)
            {
                this.SetCapacity(0, _size);
            }
        }
        /// <summary>
        /// Removes all objects from the priority queue
        /// </summary>
        public void Clear()
        {
            TurboContract.Ensures(this.Count == 0);

            for (int i = 0; i < _innerQueue.Length; i++)
            {
                _innerQueue[i].Clear();
            }

            _count = 0;
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Adds an element to the end of the list
        /// </summary>
        /// <param name="item">Element to add</param>
        public void AddLast(T item)
        {
            TurboContract.Ensures(this.Count == TurboContract.OldValue(this.Count) + 1);

            if (_size == _elemArray.Length)
            {
                this.EnsureCapacity(0, this.Count + 1);
            }
            _elemArray[_tail] = item;
            _tail             = (_tail + 1) % _elemArray.Length;
            _size++;
            _version++;
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Removes the injection from the container for the specified key
        /// </summary>
        /// <param name="key">Key</param>
        /// <returns>True if the injection was presented in container</returns>
        /// <exception cref="ObjectDisposedException"></exception>
        /// <exception cref="ObjectFrozenException"></exception>
        public bool RemoveInjection(TKey key)
        {
            TurboContract.Ensures(!this.ContainsInner(key));

            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            CheckContainerState(true);

            return(RemoveInjectionInner(key));
        }
Ejemplo n.º 26
0
        public static int FindIndex <T>(this IEnumerable <T> collection, Predicate <T> predicate)
        {
            TurboContract.Ensures(TurboContract.Result <int>() >= -1);

            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }
            if (predicate == null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            if (collection is IList <T> iList)
            {
                if (collection is List <T> list)
                {
                    return(list.FindIndex(predicate));
                }

                if (collection is T[] array)
                {
                    return(Array.FindIndex(array, predicate));
                }

                int count = iList.Count;
                for (int i = 0; i < count; i++)
                {
                    if (predicate(iList[i]))
                    {
                        return(i);
                    }
                }

                return(-1);
            }


            int index = 0;

            foreach (T elem in collection)
            {
                if (predicate(elem))
                {
                    return(index);
                }
                index++;
            }

            return(-1);
        }
Ejemplo n.º 27
0
        public ThreadPoolWorkItem TakeItem(ThreadPoolThreadLocals local, CancellationToken token)
        {
            TurboContract.Ensures(TurboContract.Result <ThreadPoolWorkItem>() != null);
            TurboContract.Assert(!_isDisposed, conditionString: "!_isDisposed");

            if (local != null)
            {
                return(_queues.Take(local.LocalQueue, token));
            }
            else
            {
                return(_queues.Take(null, token));
            }
        }
Ejemplo n.º 28
0
        public bool TryTakeItem(ThreadPoolThreadLocals local, out ThreadPoolWorkItem item)
        {
            TurboContract.Ensures(TurboContract.Result <bool>() == false || TurboContract.ValueAtReturn(out item) != null);
            TurboContract.Assert(!_isDisposed, conditionString: "!_isDisposed");

            if (local != null)
            {
                return(_queues.TryTake(local.LocalQueue, out item, 0, new CancellationToken(), true));
            }
            else
            {
                return(_queues.TryTake(null, out item, 0, new CancellationToken(), true));
            }
        }
Ejemplo n.º 29
0
        public bool TryTakeItem(ThreadPoolThreadLocals local, bool doLocalSearch, bool doWorkSteal, out ThreadPoolWorkItem item, int timeout, CancellationToken token, bool throwOnCancellation)
        {
            TurboContract.Ensures(TurboContract.Result <bool>() == false || TurboContract.ValueAtReturn(out item) != null);
            TurboContract.Assert(!_isDisposed, conditionString: "!_isDisposed");

            if (local != null)
            {
                return(_queues.TryTake(local.LocalQueue, doLocalSearch, doWorkSteal, out item, timeout, token, throwOnCancellation));
            }
            else
            {
                return(_queues.TryTake(null, doLocalSearch, doWorkSteal, out item, timeout, token, throwOnCancellation));
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Попробовать достать элемент из очереди
        /// </summary>
        /// <param name="item">Выбранный элемент</param>
        /// <returns>Удалось ли выбрать</returns>
        public bool TryTake(out ThreadPoolWorkItem item)
        {
            TurboContract.Ensures(TurboContract.Result <bool>() == false || TurboContract.ValueAtReturn(out item) != null);

            while (this.HasElements())
            {
                Segment head = _head;
                if (head.TryTake(out item))
                {
                    return(true);
                }
            }
            item = null;
            return(false);
        }