Exemple #1
0
        public void Enter(out bool taken)
        {
            // Taken is an out parameter so that we set it *inside* the critical
            // region, rather than returning it and permitting aborts to creep in.
            // Without this, the caller could take the lock, but not release it
            // because it didn't know it had to.
            taken = false;

            while (!taken)
            {
                if (isSingleProc)
                {
                    // Don't busy wait on 1-logical processor machines; try
                    // a single swap, and if it fails, drop back to EventWaitHandle.
                    Thread.BeginCriticalRegion();
                    taken = Interlocked.CompareExchange(ref state, 1, 0) == 0;
                    if (!taken)
                    {
                        Thread.EndCriticalRegion();
                    }
                }
                else
                {
                    for (int i = 0; !taken && i < outerTryCount; i++)
                    {
                        // Tell the CLR we're in a critical region;
                        // interrupting could lead to deadlocks.
                        Thread.BeginCriticalRegion();

                        // Try 'cexTryCount' times to CEX the state variable:
                        int tries = 0;
                        while (!(taken = Interlocked.CompareExchange(ref state, 1, 0) == 0) && tries++ < cexTryCount)
                        {
                            Thread.SpinWait(1);
                        }

                        if (!taken)
                        {
                            // We failed to acquire in the busy spin, mark the end
                            // of our critical region and yield to let another
                            // thread make forward progress.
                            Thread.EndCriticalRegion();
                            Thread.Sleep(0);
                        }
                    }
                }

                // If we didn't acquire the lock, block.
                if (!taken)
                {
                    available.WaitOne();
                }
            }
        }
Exemple #2
0
        public EntryBlockUC Enter()
        {
            Thread.BeginCriticalRegion();
            int ticket = Interlocked.Increment(ref _tickets);

            while (Interlocked.Add(ref _activeTicket, 0) != ticket)
            {
            }
            Thread.EndCriticalRegion();
            return(new EntryBlockUC(EntryTypeUC.Exclusive, EntryCompletion));
        }
Exemple #3
0
//--------------------------------------------------------------------------------
        public void connect()
        {
            //while (true)
            //{

            Thread.BeginCriticalRegion();
            MakeConnection();
            Thread.EndCriticalRegion();

            //}
        }
Exemple #4
0
 static void CriticalAbort()
 {
     Console.WriteLine("CritialAbort");
     Thread.BeginCriticalRegion();
     z         = new Temp();
     z.isValid = true;
     Thread.SpinWait(50);
     z.isComplete = true;
     Thread.EndCriticalRegion();
     Console.WriteLine(z.ToString());
 }
Exemple #5
0
 public override void WriteTime(string fmt, params object[] args)
 {
     Thread.BeginCriticalRegion();
     writer.Write(DateTime.Now.ToString("u") + ": ");
     writer.WriteLine(fmt, args);
     if (_autoflush)
     {
         Flush();
     }
     Thread.EndCriticalRegion();
 }
Exemple #6
0
 /// <summary>
 /// Aborts execution of the thread, if there is any.
 /// </summary>
 public void Abort()
 {
     Thread.BeginCriticalRegion();
     executing = false;
     Thread.EndCriticalRegion();
     endExecution();
     if (thread != null)
     {
         thread.Abort();
     }
 }
        private StorageInfo CreateStorageInfo()
        {
            // we do our own locking, tell hosts this is a bad time to interrupt us.
#if !SILVERLIGHT
            Thread.BeginCriticalRegion();
#endif
            StorageInfo[] curStorage = Updating;
            try {
                int         threadId = Thread.CurrentThread.ManagedThreadId;
                StorageInfo newInfo  = new StorageInfo(Thread.CurrentThread);

                // set to updating while potentially resizing/mutating, then we'll
                // set back to the current value.
                while ((curStorage = Interlocked.Exchange(ref _stores, Updating)) == Updating)
                {
                    // another thread is already updating...
                    Thread.Sleep(0);
                }

                // check and make sure we have a space in the array for our value
                if (curStorage == null)
                {
                    curStorage = new StorageInfo[threadId + 1];
                }
                else if (curStorage.Length <= threadId)
                {
                    StorageInfo[] newStorage = new StorageInfo[threadId + 1];
                    for (int i = 0; i < curStorage.Length; i++)
                    {
                        // leave out the threads that have exited
                        if (curStorage[i] != null && curStorage[i].Thread.IsAlive)
                        {
                            newStorage[i] = curStorage[i];
                        }
                    }
                    curStorage = newStorage;
                }

                // create our StorageInfo in the array, the empty check ensures we're only here
                // when we need to create.
                Debug.Assert(curStorage[threadId] == null || curStorage[threadId].Thread != Thread.CurrentThread);

                return(curStorage[threadId] = newInfo);
            } finally {
                if (curStorage != Updating)
                {
                    // let others access the storage again
                    Interlocked.Exchange(ref _stores, curStorage);
                }
#if !SILVERLIGHT
                Thread.EndCriticalRegion();
#endif
            }
        }
Exemple #8
0
 public void Enter()
 {
     Thread.BeginCriticalRegion();
     while (Interlocked.Exchange(ref this._lockState, 1) != 0)
     {
         while (Thread.VolatileRead(ref this._lockState) == 1)
         {
             SpinLock.StallThread();
         }
     }
 }
        public void compute()
        {
            Thread current = Thread.CurrentThread;

            current.Priority = ThreadPriority.Highest;
            int position;

            Thread.BeginCriticalRegion();
            position = mutex; mutex++;
            Thread.EndCriticalRegion();
            solve(position);
        }
Exemple #10
0
            private void StartDisposingThread()
            {
                if (_disposingThread != null && _disposingThread.IsAlive)
                {
                    return;
                }

                _disposingThread = new Thread(
                    () =>
                {
                    Thread.Sleep(5000);
                    while (true)
                    {
                        TimeSpan span;
                        lock (this)
                        {
                            if (!_dereferenceTime.HasValue)
                            {
                                return;
                            }
                            if (_dereferenceTime.Value.AddMilliseconds(4500) < DateTime.Now)
                            {
                                if (_connection != null)
                                {
#if !NETCOREAPP1_0
                                    try
                                    {
                                        Thread.BeginCriticalRegion();
#endif
                                    DbConnection connection = _connection;
                                    _connection             = null;
                                    connection.Dispose();
                                    _disposingThread = null;
#if !NETCOREAPP1_0
                                }
                                finally
                                {
                                    Thread.EndCriticalRegion();
                                }
#endif
                                }
                                return;
                            }
                            span = _dereferenceTime.HasValue ? (_dereferenceTime.Value.AddMilliseconds(5000) - DateTime.Now) : TimeSpan.Zero;
                        }
                        if (span > TimeSpan.Zero)
                        {
                            Thread.Sleep(span);
                        }
                    }
                });
                _disposingThread.Start();
            }
Exemple #11
0
 public bool TryEnterWriteLock(int millisecondsTimeout)
 {
     Thread.BeginCriticalRegion();
     this.lockHeldRegion.Value.Enter();
     if (!this.rwLock.TryEnterWriteLock(millisecondsTimeout))
     {
         this.lockHeldRegion.Value.Exit();
         Thread.EndCriticalRegion();
         return(false);
     }
     return(true);
 }
Exemple #12
0
        /// <summary>
        /// If a writer is open, flush, close, and dispose it.
        /// </summary>
        public static void Close()
        {
            Thread.BeginCriticalRegion();
            if (writer != null)
            {
                Flush();
                writer.Close();
                writer.Dispose();
            }

            Thread.EndCriticalRegion();
        }
Exemple #13
0
        /// <summary>
        /// If log is already open with the same filename, do nothing.
        /// Otherwise open (in append mode, if file exists).
        /// </summary>
        /// <remarks>
        /// Be aware that log files that are never truncated can become very large.
        /// </remarks>
        /// <param name="fileName">the filename</param>
        public static void Reopen(string fileName)
        {
            Thread.BeginCriticalRegion();
            FileInfo temp = new FileInfo(fileName);

            if (Ready && _fInfo.FullName == temp.FullName)
            {
                return;
            }
            OpenAppend(fileName);
            Thread.EndCriticalRegion();
        }
Exemple #14
0
        internal void RemoveClient(SSLClient client)
        {
            Thread.BeginCriticalRegion();

            lock (clientList)
            {
                client.Dispose();
                clientList.Remove(client);
            }

            Thread.EndCriticalRegion();
        }
Exemple #15
0
        private void ProcessAsyncOperations(object ownerForm)
        {
            var f = (TContext)ownerForm;
            var w = _OperationSemaphore;

            while (true)
            {
                w.WaitOne();

                Thread.BeginCriticalRegion();
                try
                {
                    if (_OperationQueue.Count > 0)
                    {
                        var op = AsyncDeQueueOperation();
                        try
                        {
                            f.AsyncOperationBegins(op.Name);
                            var res = op.Action(f);
                            if (op.Notifier != null)
                            {
                                op.Notifier(f, res);
                            }
                        }
                        finally
                        {
                            f.AsyncOperationsCompleted();
                        }
                    }
                }
                catch (SqlCommandException e)
                {
                    _OperationQueue.Clear();
                    f.AsyncError(e.Message);
                }
                catch (InvalidDBVersionException e)
                {
                    _OperationQueue.Clear();
                    f.AsyncError(string.Format("Invalid DB Version: {0}. Cannot run script!!!", e.Version));
                }
                catch (Exception e)
                {
                    _OperationQueue.Clear();
                    f.AsyncError(e.Message);
                }
                finally
                {
                    Thread.EndCriticalRegion();
                    OperationCompleted();
                }
            }
        }
Exemple #16
0
        private static void ProcessMessages()
        {
            while (true)
            {
                try
                {
                    foreach (string client in clients.Keys)
                    {
                        if (!clients[client].StillConnected)
                        {
                            Thread.BeginCriticalRegion();
                            clients.Remove(client);
                            clients[client].Dispose();
                            Thread.EndCriticalRegion();
                            foreach (string c in clients.Keys)
                            {
                                if (!c.Equals(client))
                                {
                                    clients[c].SendMessage(string.Format("{0} has left the server.", client));
                                }
                            }
                            continue;
                        }
                        if (!clients[client].HasMessages)
                        {
                            continue;
                        }

                        Message nextMessage = clients[client].GetNextMessage();

                        foreach (string recipient in nextMessage.destinations)
                        {
                            if (recipient.Equals("server"))
                            {
                                serverMessages.Add(nextMessage);
                                continue;
                            }

                            if (clients.ContainsKey(recipient))
                            {
                                clients[recipient].SendMessage(nextMessage);
                            }
                            else
                            {
                                clients[client].SendMessage(string.Format("{0} doesn't seem to be connected.", recipient));
                            }
                        }
                    }
                }
                catch { }
            }
        }
Exemple #17
0
 public static void ErrorLog(Exception ex, String ErrorData, String FileName)
 {
     try
     {
         Thread.BeginCriticalRegion();
         String ErrorFilename = FileName;
         Utility.LogFile(ErrorFilename, ErrorData);
         Utility.LogFile(ErrorFilename, ex.Message);
         Utility.LogFile(ErrorFilename, ex.StackTrace);
         Thread.EndCriticalRegion();
     }
     catch { }
 }
Exemple #18
0
        /// <summary>
        /// Releases the lock.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">lock is not held</exception>
        /// <exception cref="T:System.Threading.SynchronizationLockException">Thread ownership tracking is enabled, and the current thread is not the owner of this lock.</exception>
        public void Release()
        {
            Thread.BeginCriticalRegion();
            if ((this.mOwner & LockAnonymousOwned) == LockUnowned)
            {
                Thread.EndCriticalRegion();
                throw new InvalidOperationException("lock is not held");
            }

            Interlocked.Decrement(ref this.mOwner);

            Thread.EndCriticalRegion();
        }
Exemple #19
0
 /// <summary>
 /// Debug program.
 /// </summary>
 public void Debug()
 {
     cpu.Constants.GetRegister("pc").Val = entryPoint;
     Thread.BeginCriticalRegion();
     next = 0;
     Thread.EndCriticalRegion();
     Thread.BeginCriticalRegion();
     stepByStepMode = false;
     Thread.EndCriticalRegion();
     thread = new Thread(new ThreadStart(executeStepByStep));
     Console.WriteLine("Executor thread id = " + thread.ManagedThreadId);
     thread.Start();
 }
Exemple #20
0
        public void compute()
        {
            Thread current = Thread.CurrentThread;

            current.Priority = ThreadPriority.Highest;
            int secondNode;

            Thread.BeginCriticalRegion();
            secondNode = mutex;
            mutex++;
            Thread.EndCriticalRegion();
            solve(secondNode);
        }
Exemple #21
0
        public static void Save(Config config, string filename)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            Thread.BeginCriticalRegion();

            Stream stream = null;

            XmlTextWriter writer     = null;
            XmlSerializer serializer = null;

            try {
                FileInfo file = new FileInfo(filename);

                if (config.Avatar != null && config.Avatar.SmallBytes.Length > 0)
                {
                    File.WriteAllBytes(Path.Combine(file.Directory.FullName, "avatar_small.jpg"), config.Avatar.SmallBytes);
                    File.WriteAllBytes(Path.Combine(file.Directory.FullName, "avatar_large.jpg"), config.Avatar.LargeBytes);
                }

                stream = file.Open(FileMode.Create, FileAccess.Write);
                writer = new XmlTextWriter(stream, Encoding.UTF8);

                writer.Formatting  = Formatting.Indented;
                writer.Indentation = 2;
                writer.IndentChar  = '\x20';

                serializer = new XmlSerializer(typeof(Config));
                serializer.Serialize(writer, config);

                writer.Flush();
            }
            catch (UnauthorizedAccessException) { }
            finally {
                if (writer != null)
                {
                    writer.Close();
                }

                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }

            Thread.EndCriticalRegion();
        }
Exemple #22
0
        public void ReleaseLock(LockToken <T> token, LockRuleset rules)
        {
            if (!_locks.TryGetValue(token.LockedObject, out var h))
            {
                throw new InvalidOperationException("Object not locked");
            }
            var lockType = token.LockLevel;
            var matrix   = rules.LockMatrix;

            unchecked
            {
                if (matrix.IsSelfShared(lockType))
                {
                    int i;
                    Thread.BeginCriticalRegion();

                    do                                                             //переводим комбинацию блокировок в новое состояние и поднимаем флаг проверки разделямых блокировок
                    {
                        i = (int)(h.LockInfo & LockMatrix.SharenessCheckLockDrop); //мы исключаем из возможных переходы, результатом которых будет поднятый флаг проверки разделяемой блокировки (проверки разделяемой блокировки смогут пересечься)
                    } while (Interlocked.CompareExchange(ref h.LockInfo, i | (int)LockMatrix.SharenessCheckLock, i) != i);

                    if (h.GetSharedLockCount(matrix.SelfSharedLockShift(lockType)) == 0)//если текущий переход убирает существующую разделяемую блокировку (т.е. их сейчас нет).
                    {
                        //делаем переход в новое состояние
                        h.LockInfo = (int)matrix.ExitPair(lockType, (int)(LockMatrix.SharenessCheckLockDrop & (uint)h.LockInfo)).Value.BlockEntrance;
                    }
                    else//если же видим, что освобождение текущей блокировки только уменьшает количество разделяемых блокировок её типа
                    {
                        var sharedLockCount = h.DecrLock(matrix.SelfSharedLockShift(lockType));//то уменьшаем счётчик блокировок
                        Debug.Print($"{sharedLockCount}");
                        h.LockInfo = h.LockInfo & (int)LockMatrix.SharenessCheckLockDrop;//и сбрасываем флаг проверки
                    }
                    Thread.EndCriticalRegion();
                }
                else
                {
                    while (true)
                    {
                        var entrancePair = matrix.ExitPair(lockType, (int)(h.LockInfo & LockMatrix.SharenessCheckLockDrop));
                        if (entrancePair.HasValue)
                        {
                            if (Interlocked.CompareExchange(ref h.LockInfo, (int)entrancePair.Value.BlockEntrance,
                                                            (int)entrancePair.Value.BlockExit) == (int)entrancePair.Value.BlockExit)
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
Exemple #23
0
        public void AutoSizeColumn(TreeColumn col, ColumnHeaderAutoResizeStyle headerAutoSize)
        {
            if (!Columns.Contains(col))
            {
                throw new ArgumentException("column is not a part of treeviewadv", "col");
            }

            if (headerAutoSize == ColumnHeaderAutoResizeStyle.None)
            {
                return;
            }

            Thread.BeginCriticalRegion();

            foreach (TreeNodeAdv tna in this.VisibleNodes)
            {
                foreach (NodeControlInfo nci in this.GetNodeControls(tna))
                {
                    if (nci.Control.ParentColumn == col)
                    {
                        int nWidth = 0;

                        Size sizeCntrl = nci.Control.GetActualSize(tna, this._measureContext);

                        if (col.Index == 0)
                        {
                            nWidth += nci.Bounds.X;
                        }

                        if (!sizeCntrl.IsEmpty)
                        {
                            col.Width = Math.Max(col.Width, (sizeCntrl.Width + nWidth));
                        }

                        if (headerAutoSize == ColumnHeaderAutoResizeStyle.HeaderSize)
                        {
                            //Size sizeText = TextRenderer.MeasureText(col.Header, this._measureContext.Font);

                            SizeF sizeText = this._measureContext.Graphics.MeasureString(col.Header, this._measureContext.Font);

                            if (!sizeText.IsEmpty)
                            {
                                col.Width = Math.Max(col.Width, (int)sizeText.Width);
                            }
                        }
                    }
                }
            }

            Thread.EndCriticalRegion();
        }
Exemple #24
0
 public static void ErrorLog(Exception ex, String ErrorData)
 {
     try
     {
         if (Settings.GetValue("ErrorsToFile") == true)
         {
             Thread.BeginCriticalRegion();
             String ErrorFilename = Constants.ApplicationLogFile; // Settings.GetValue("ErrorFileName");
             ErrorLog(ex, ErrorData, ErrorFilename);
             Thread.EndCriticalRegion();
         }
     }
     catch { }
 }
Exemple #25
0
 /// <summary>
 /// Write a plain string to the output, then a newline.
 /// </summary>
 /// <param name="output">the string</param>
 /// <returns>the string</returns>
 public static string WriteLine(string output)
 {
     Thread.BeginCriticalRegion();
     if (Ready)
     {
         _writer.WriteLine(output);
         if (_autoflush)
         {
             Flush();
         }
     }
     Thread.EndCriticalRegion();
     return(output + "\n");
 }
Exemple #26
0
        public void AcquireWriterLock()
        {
            Thread.BeginCriticalRegion();

            while (Interlocked.CompareExchange(ref fBusy, 1, 0) != 0)
            {
                Thread.Sleep(1);
            }

            while (Interlocked.CompareExchange(ref fReadCount, 0, 0) != 0)
            {
                Thread.Sleep(1);
            }
        }
Exemple #27
0
        public bool Return(T item)
        {
            if (m_count >= m_items.Length)
            {
                return(false);
            }

            Thread.BeginCriticalRegion();

            m_items[m_count++] = item;

            Thread.EndCriticalRegion();
            return(true);
        }
Exemple #28
0
        public void SimulationTick()
        {
            if (NumberContinuousSignals == 0)
            {
                SimulatedSignal         = GetSimulatedSignal();
                NumberContinuousSignals = RanSim.Next(MinSimChange, MaxSimChange);

                if (AdjustToTarget)
                {
                    if (MinSimChange > MinSimChangeTarget)
                    {
                        MinSimChange--;
                    }

                    if (MaxSimChange > MaxSimChangeTarget)
                    {
                        MaxSimChangeTarget--;
                    }
                }

                if (SimulatedSignal == 0)
                {
                    NumberContinuousSignals += 3;
                }
                bx.SignalProcessor.PerformDiscreteSignalAction(SimulatedSignal, FeedbackType.Audio);
                bx.SignalProcessor.PerformDiscreteSignalAction(SimulatedSignal, FeedbackType.Keyboard);
                bx.SignalProcessor.PerformDiscreteSignalAction(SimulatedSignal, FeedbackType.Visual);
            }
            else if (NumberContinuousSignals > 0)
            {
                if (SimulatedSignal < 0 || SimulatedSignal > 1)
                {
                    SimulatedSignal = GetSimulatedSignal();
                }
                bx.SignalProcessor.PerformDiscreteSignalAction(SimulatedSignal, FeedbackType.Audio);
                bx.SignalProcessor.PerformDiscreteSignalAction(SimulatedSignal, FeedbackType.Keyboard);
                bx.SignalProcessor.PerformDiscreteSignalAction(SimulatedSignal, FeedbackType.Visual);
                Thread.BeginCriticalRegion();
                if (NumberContinuousSignals > 0)
                {
                    NumberContinuousSignals--;
                    Thread.EndCriticalRegion();
                }
            }
            else
            {
                throw new ApplicationException("Simulator error");
            }
        }
Exemple #29
0
        /// <summary>
        /// Decreases the reference count of the object.
        /// </summary>
        /// <param name="count">The number of times to dereference the object.</param>
        /// <param name="managed">Whether to dispose managed resources.</param>
        /// <returns>The new reference count.</returns>
        public int Dereference(int count, bool managed)
        {
            // Initial parameter validation.
            if (count == 0)
                return Interlocked.Add(ref _refCount, 0);
            if (count < 0)
                throw new ArgumentException("Cannot dereference a negative number of times.");

            // Critical, prevent thread abortion.
            Thread.BeginCriticalRegion();

            try
            {
                if (!_owned)
                    return 0;

#if ENABLE_STATISTICS
                // Statistics.
                Interlocked.Add(ref _dereferencedCount, count);
#endif

                // Decrease the reference count.
                int newRefCount = Interlocked.Add(ref _refCount, -count);

                // Should not ever happen.
                if (newRefCount < 0)
                    throw new InvalidOperationException("Reference count cannot be negative.");

                // Dispose the object if the reference count is 0.
                if (newRefCount == 0 && !_disposed)
                {
                    // If the dispose object method throws an exception, nothing bad 
                    // should happen if it does not invalidate any state.
                    this.DisposeObject(managed);
                    // Prevent the object from being disposed twice.
                    _disposed = true;

#if ENABLE_STATISTICS
                    Interlocked.Increment(ref _freedCount);
#endif
                }

                return newRefCount;
            }
            finally
            {
                Thread.EndCriticalRegion();
            }
        }
 private bool EnterLock()
 {
     Thread.BeginCriticalRegion();
     // If resource available, set it to in-use and return
     if (Interlocked.Exchange(
             ref _lock, c_lsOwned) == c_lsFree)
     {
         return(true);
     }
     else
     {
         Thread.EndCriticalRegion();
         return(false);
     }
 }