コード例 #1
1
        private static void Main(string[] args)
        {
            SpinLock slock = new SpinLock(false);
            long sum1 = 0;
            long sum2 = 0;
            Parallel.For(0, 10000, i => { sum1 += i; });

            Parallel.For(0, 10000, i =>
            {
                bool lockTaken = false;
                try
                {
                    slock.Enter(ref lockTaken);
                    sum2 += i;
                }
                finally
                {
                    if (lockTaken)
                        slock.Exit(false);
                }
            });

            Console.WriteLine("Num1的值为:{0}", sum1);
            Console.WriteLine("Num2的值为:{0}", sum2);
        }
コード例 #2
1
        // SpinLock работает на interlocked-конструкции
        // соответственно, применять можно, когда
        // время нахождения в критической секции минимально
        // и/или необходимо много блокировок
        public static void SpinLockUsage()
        {
            SpinLock spinLock = new SpinLock();
            bool lockTaken = false;

            spinLock.Enter(ref lockTaken);

            // код критической секции

            spinLock.Exit();
        }
コード例 #3
1
 static void Main(string[] args)
 {
     var slock = new SpinLock();
     bool taken = false;
     try
     {
         slock.Enter(ref taken);
         DoSomething();
     }
     finally
     {
         if (taken) slock.Exit();
     }
 }
コード例 #4
0
ファイル: PrecisionInputTimer.cs プロジェクト: rmc00/gsf
        /// <summary>
        /// Create a new <see cref="PrecisionInputTimer"/> class.
        /// </summary>
        /// <param name="framesPerSecond">Desired frame rate for <see cref="PrecisionTimer"/>.</param>
        internal PrecisionInputTimer(int framesPerSecond)
        {
            // Create synchronization objects
            m_timerTickLock = new SpinLock();
            m_frameWaitHandleA = new ManualResetEventSlim(false);
            m_frameWaitHandleB = new ManualResetEventSlim(false);
            m_useWaitHandleA = true;
            m_framesPerSecond = framesPerSecond;

            // Create a new precision timer for this timer state
            m_timer = new PrecisionTimer();
            m_timer.Resolution = 1;
            m_timer.Period = 1;
            m_timer.AutoReset = true;

            // Attach handler for timer ticks
            m_timer.Tick += m_timer_Tick;

            m_frameWindowSize = (int)Math.Round(1000.0D / framesPerSecond) * 2;
            m_frameMilliseconds = new int[framesPerSecond];

            for (int frameIndex = 0; frameIndex < framesPerSecond; frameIndex++)
            {
                m_frameMilliseconds[frameIndex] = (int)(1.0D / framesPerSecond * (frameIndex * 1000.0D));
            }

            // Start high resolution timer on a separate thread so the start
            // time can synchronized to the top of the millisecond
            ThreadPool.QueueUserWorkItem(SynchronizeInputTimer);
        }
コード例 #5
0
ファイル: RwLock.cs プロジェクト: eeastwood/COMP-410_Fall-15
 public RwLock()
 {
     // most similar to this: ReaderWriterLockSlim
     _numReaders = 0;
     _numWriters = 0;
     _waitingWriters = 0;
     _lock = new SpinLock();
 }
コード例 #6
0
ファイル: FrameQueue.cs プロジェクト: rmc00/gsf
        private bool m_disposed;                                        // Object disposed flag

        #endregion

        #region [ Constructors ]

        /// <summary>
        /// Creates a new <see cref="FrameQueue"/>.
        /// </summary>
        internal FrameQueue(CreateNewFrameFunction createNewFrame)
        {
            m_createNewFrame = createNewFrame;
            m_frameList = new LinkedList<TrackingFrame>();
            m_frameHash = new ConcurrentDictionary<long, TrackingFrame>();
            m_queueLock = new SpinLock();
            m_downsamplingMethod = DownsamplingMethod.LastReceived;
        }
コード例 #7
0
		public void RecursionExceptionTest ()
		{
			sl = new SpinLock (true);
			bool taken = false, taken2 = false;

			sl.Enter (ref taken);
			Assert.IsTrue (taken, "#1");
			sl.Enter (ref taken2);
		}
コード例 #8
0
ファイル: ByteArrayPool.cs プロジェクト: webconfig/Bombs
        /// <summary>
        /// Creates the pool with numberOfBuffers arrays where each buffer is of bufferLength length.
        /// </summary>
        internal Bucket(int bufferLength, int numberOfBuffers, int poolId)
        {
#if SERVERSIDE
            _lock = new System.Threading.SpinLock(System.Diagnostics.Debugger.IsAttached);     // only enable thread tracking if debugger is attached; it adds non-trivial overheads to Enter/Exit
#endif
            _buffers      = new T[numberOfBuffers][];
            _bufferLength = bufferLength;
            _poolId       = poolId;
        }
コード例 #9
0
 public static void Initialize()
 {
     if (s_Types == null)
     {
         ObjectOffset     = UnsafeUtility.SizeOf <ObjectOffsetType>();
         s_CreateTypeLock = new System.Threading.SpinLock();
         s_Types          = new TypeInfo[0x2800];
         s_Count          = 0;
         s_Count++;
         s_Types[s_Count] = new TypeInfo(null, 0, TypeCategory.ComponentData, FastEquality.TypeInfo.Null, null, 0L, -1, 0);
         s_Count++;
         s_Types[s_Count] = new TypeInfo(typeof(Entity), sizeof(Entity), TypeCategory.EntityData, FastEquality.CreateTypeInfo(typeof(Entity)), EntityRemapUtility.CalculateEntityOffsets(typeof(Entity)), 0L, -1, sizeof(Entity));
     }
 }
コード例 #10
0
        internal NativeBufferBucket(int elementsInBuffer, int numberOfBuffers)
        {
            _index = 0;
            _elementsInBuffer = elementsInBuffer;
            _lock = new SpinLock();

            int bufferLength = numberOfBuffers * _elementsInBuffer;
            _allocatedMemory = Marshal.AllocHGlobal(bufferLength * Marshal.SizeOf(typeof(byte)));
            _buffers = new NativeBuffer?[numberOfBuffers];

            for (int i = 0; i < bufferLength; i+= _elementsInBuffer)
            {
                _buffers[i / _elementsInBuffer] = new NativeBuffer((_allocatedMemory + i).ToPointer(), _elementsInBuffer);
            }
        }
コード例 #11
0
ファイル: SpinLockTests.cs プロジェクト: mesheets/Theraot-CF
        public void IsHeldByCurrentThreadTest()
        {
            bool lockTaken = false;

            sl.Enter(ref lockTaken);
            Assert.IsTrue(lockTaken, "#1");
            Assert.IsTrue(sl.IsHeldByCurrentThread, "#2");

            lockTaken = false;
            sl = new SpinLock(true);

            sl.Enter(ref lockTaken);
            Assert.IsTrue(lockTaken, "#3");
            Assert.IsTrue(sl.IsHeldByCurrentThread, "#4");
        }
コード例 #12
0
		public void SemanticCorrectnessTest ()
		{
			sl = new SpinLock (false);

			bool taken = false;
			bool taken2 = false;

			sl.Enter (ref taken);
			Assert.IsTrue (taken, "#1");
			sl.TryEnter (ref taken2);
			Assert.IsFalse (taken2, "#2");
			sl.Exit ();

			sl.TryEnter (ref taken2);
			Assert.IsTrue (taken2, "#3");
		}
コード例 #13
0
        private MongoHelperProvider()
        {
            _spinLock = new SpinLock();
            _mongoHelpers = new Dictionary<string, IMongoHelper>();

            var mongoDbConfig = ConfigurationManager.GetSection(SectionName);

            if (mongoDbConfig is MongoConfig)
            {
                CreateBasicHelpers((MongoConfig)mongoDbConfig);
                return;
            }
            if(mongoDbConfig is MongoFullConfig)
            {
                CreateExtendedHelpers((MongoFullConfig)mongoDbConfig);
            }
        }
コード例 #14
0
        static void Main(string[] args) {

            // create the bank account instance
            BankAccount account = new BankAccount();

            // create the spinlock
            SpinLock spinlock = new SpinLock();

            // create an array of tasks
            Task[] tasks = new Task[10];

            for (int i = 0; i < 10; i++) {
                // create a new task
                tasks[i] = new Task(() => {
                    // enter a loop for 1000 balance updates
                    for (int j = 0; j < 1000; j++) {
                        bool lockAcquired = false;
                        try {
                            spinlock.Enter(ref lockAcquired);
                            // update the balance
                            account.Balance = account.Balance + 1;
                        } finally {
                            if (lockAcquired) spinlock.Exit();
                        }
                    }
                });
                // start the new task
                tasks[i].Start();
            }

            // wait for all of the tasks to complete
            Task.WaitAll(tasks);

            // write out the counter value
            Console.WriteLine("Expected value {0}, Balance: {1}",
                10000, account.Balance);

            // wait for input before exiting
            Console.WriteLine("Press enter to finish");
            Console.ReadLine();
        }
コード例 #15
0
        public DepotProcessor(SteamClient client)
        {
            UpdateScript = Path.Combine(Application.Path, "files", "update.sh");
            UpdateScriptLock = new SpinLock();
            DepotLocks = new Dictionary<uint, byte>();

            DepotThreadPool = new SmartThreadPool();
            DepotThreadPool.Concurrency = Settings.Current.FullRun == FullRunState.WithForcedDepots ? 15 : 5;
            DepotThreadPool.Name = "Depot Thread Pool";

            CDNClient = new CDNClient(client);

            FileDownloader.SetCDNClient(CDNClient);

            CDNServers = new List<string>
            {
                "cdn.level3.cs.steampowered.com",
                "cdn.akamai.cs.steampowered.com",
                "cdn.highwinds.cs.steampowered.com"
            };
        }
コード例 #16
0
ファイル: SmartSpinlock.cs プロジェクト: Paul1nh0/Singularity
        public SmartSpinlock(SpinLock.Types type)
        {
#if SINGULARITY_MP
            this.spin = new SpinLock(type);
#endif
        }
コード例 #17
0
 /// <summary>
 /// SystemThreading_SpinLockDebugView constructor
 /// </summary>
 /// <param name="spinLock">The SpinLock to be proxied.</param>
 public SystemThreading_SpinLockDebugView(SpinLock spinLock)
 {
     // Note that this makes a copy of the SpinLock (struct). It doesn't hold a reference to it.
     m_spinLock = spinLock;
 }
コード例 #18
0
 /// <summary>Initializes an instance of the SpinLockClass class.</summary>
 /// <param name="enableThreadOwnerTracking">
 /// Controls whether the SpinLockClass should track
 /// thread-ownership fo the lock.
 /// </param>
 public SpinLockClass(bool enableThreadOwnerTracking)
 {
     this._spinLock = new SpinLock(enableThreadOwnerTracking);
 }
コード例 #19
0
 public SpinLock()
 {
     _lock = new System.Threading.SpinLock();
 }
コード例 #20
0
ファイル: SpinLockTests.cs プロジェクト: modulexcite/IL2JS
        /// <summary>
        /// Test SpinLock.Enter by launching n threads that increment a variable inside a critical section
        /// the final count variable must be equal to n
        /// </summary>
        /// <param name="threadsCount">Number of threads that call enter/exit</param>
        /// <returns>True if succeeded, false otherwise</returns>
        private static bool RunSpinLockTest0_Enter(int threadsCount, bool enableThreadIDs)
        {
            TestHarness.TestLog("SpinLock.Enter(" + threadsCount + " threads)");

            // threads array
            Thread[] threads = new Thread[threadsCount];
            //spinlock object
            SpinLock slock = new SpinLock(enableThreadIDs);
            // scceeded threads counter
            int succeeded = 0;
            // Semaphore used to make sure that there is no other threads in the critical section
            Semaphore semaphore = new Semaphore(1, 1);

            for (int i = 0; i < threadsCount; i++)
            {
                threads[i] = new Thread(delegate()
                {
                    bool lockTaken = false;
                    try
                    {
                        slock.Enter(ref lockTaken);
                        //use semaphore to make sure that no other thread inside the critical section
                        if (!semaphore.WaitOne(0, false))
                        {
                            // This mean that there is another thread in the critical section
                            return;
                        }
                        succeeded++;
                        if (slock.IsThreadOwnerTrackingEnabled && !slock.IsHeldByCurrentThread)
                        {
                            // lock is obtained successfully
                            succeeded--;
                        }

                    }
                    catch
                    {
                        // decrement the count in case of exception
                        succeeded--;
                    }
                    finally
                    {
                        semaphore.Release();
                        if (lockTaken)
                        {
                            slock.Exit();
                        }
                    }
                });
                threads[i].Start();

            }
            // wait all threads
            for (int i = 0; i < threadsCount; i++)
            {
                threads[i].Join();
            }
            // count must be equal to the threads count
            if (succeeded != threadsCount)
            {
                TestHarness.TestLog("SpinLock.Enter() failed, actual count: " + succeeded + " expected: " + threadsCount);
                return false;
            }
            TestHarness.TestLog("SpinLock.Enter() passed.");
            return true;
        }
コード例 #21
0
ファイル: SpinLockTests.cs プロジェクト: modulexcite/IL2JS
        /// <summary>
        /// Test Exit
        /// </summary>
        /// <returns>True if succeeded, false otherwise</returns>
        private static bool RunSpinLockTest4_Exit(bool enableThreadIDs)
        {
            TestHarness.TestLog("SpinLock.Exit()");
            Exception exception = null;
            SpinLock slock = new SpinLock(enableThreadIDs);
            bool lockTaken = false;
            slock.Enter(ref lockTaken);
            slock.Exit();
            if (enableThreadIDs && slock.IsHeldByCurrentThread)
            {
                TestHarness.TestLog("SpinLock.Exit() failed, IsHeld is true after calling Exit");
                return false;
            }

            // Calling Exit without owning the lock
            try
            {
                slock.Exit();
            }
            catch (Exception ex)
            {
                // SynchronizationLockException must be thrown
                exception = ex;
            }
            if (enableThreadIDs)
            {
                if (exception == null || exception.GetType() != typeof(SynchronizationLockException))
                {
                    TestHarness.TestLog(@"SpinLock.Exit() failed, calling Exit without owning the lock");
                    return false;
                }
            }

            TestHarness.TestLog("SpinLock.Exit() passed.");
            return true;

        }
コード例 #22
0
ファイル: SpinLockTests.cs プロジェクト: modulexcite/IL2JS
        /// <summary>
        /// Test TryEnter invalid cases
        /// </summary>
        /// <returns>True if succeeded, false otherwise</returns>
        private static bool RunSpinLockTest3_TryEnter(bool enableThreadIDs)
        {
            TestHarness.TestLog("SpinLock.TryEnter(invalid cases)");
            Exception exception = null;
            SpinLock slock = new SpinLock(enableThreadIDs);
            bool lockTaken = false;
            #region Recursive lock
            if (enableThreadIDs) // only valid if thread IDs are on
            {

                // Test recursive locks
                slock.Enter(ref lockTaken);
                try
                {
                    if (lockTaken)
                    {

                        bool dummy = false;
                        // reacquire the lock
                        slock.Enter(ref dummy);
                    }
                }
                catch (Exception ex)
                {
                    // LockRecursionException must be thrown
                    exception = ex;
                }
                if (lockTaken)
                {
                    slock.Exit();
                    //TODO: uncomment after finishing type forwarding in clr integration
                    if (exception == null /*|| exception.GetType() != typeof(LockRecursionException)*/)
                    {
                        TestHarness.TestLog("SpinLock.TryEnter() failed, recursive locks without exception");
                        return false;
                    }
                    if (slock.IsHeldByCurrentThread)
                    {
                        TestHarness.TestLog("SpinLock.TryEnter() failed, IsHeld is true after calling Exit");
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            #endregion
            #region timeout > int.max
            // Test invalid argument handling, too long timeout
            exception = null;
            try
            {
                lockTaken = false;
                slock.TryEnter(TimeSpan.MaxValue, ref lockTaken);

            }
            catch (Exception ex)
            {
                exception = ex;
            }
            if (exception == null || exception.GetType() != typeof(ArgumentOutOfRangeException))
            {
                TestHarness.TestLog(@"SpinLock.TryEnter() failed, timeout.Totalmilliseconds > int.maxValue
                 without throwing ArgumentOutOfRangeException " + exception);
                return false;
            }
            #endregion

            #region Timeout > int.max
            // Test invalid argument handling, timeout < -1
            exception = null;
            try
            {
                lockTaken = false;
                slock.TryEnter(-2, ref lockTaken);
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            if (exception == null || exception.GetType() != typeof(ArgumentOutOfRangeException))
            {
                TestHarness.TestLog(@"SpinLock.TryEnter() failed, timeout < -1
                 without throwing ArgumentOutOfRangeException");
                return false;
            }
            #endregion

            TestHarness.TestLog("SpinLock.TryEnter() passed.");
            return true;
        }
コード例 #23
0
ファイル: SpinLockTests.cs プロジェクト: modulexcite/IL2JS
        /// <summary>
        /// Test SpinLock.TryEnter(Timespan) by generating random timespan milliseconds
        /// </summary>
        /// <param name="threadsCount">Number of threads that call enter/exit</param>
        /// <returns>True if succeeded, false otherwise</returns>
        private static bool RunSpinLockTest2_TryEnter(int threadsCount, bool enableThreadIDs)
        {
            TestHarness.TestLog("SpinLock.TryEnter(" + threadsCount + " threads)");

            Thread[] threads = new Thread[threadsCount];
            SpinLock slock = new SpinLock(enableThreadIDs);
            int succeeded = 0;
            int failed = 0;

            // Run threads
            for (int i = 0; i < threadsCount; i++)
            {
                threads[i] = new Thread(delegate(object x)
                {
                    // Generate random timespan
                    Random rand = new Random(33);
                    bool lockTaken = false;
                    TimeSpan time = TimeSpan.FromMilliseconds(rand.Next(-1, 20));
                    slock.TryEnter(time, ref lockTaken);
                    if (lockTaken)
                    {
                        // add some delay in the critical section
                        Thread.Sleep(15);
                        Interlocked.Increment(ref succeeded);
                        slock.Exit();
                    }
                    else
                    {
                        // Failed to get the lock within the timeout
                        Interlocked.Increment(ref failed);
                    }
                });
                threads[i].Start(i);
            }
            // Wait all threads
            for (int i = 0; i < threadsCount; i++)
            {
                threads[i].Join();
            }
            // succeeded + failed must be equal to the threads count.
            if (succeeded + failed != threadsCount)
            {
                TestHarness.TestLog("SpinLock.TryEnter() failed, actual count: " + (succeeded + failed) +
                    " expected :" + threadsCount);
                return false;
            }
            TestHarness.TestLog("SpinLock.TryEnter() passed.");
            return true;
        }
コード例 #24
0
ファイル: SpinLock.cs プロジェクト: wwkkww1983/ZJCredit
 public SystemThreading_SpinLockDebugView(SpinLock spinLock)
 {
     this.m_spinLock = spinLock;
 }
コード例 #25
0
 /// <summary>Initializes an instance of the SpinLockClass class.</summary>
 public SpinLockClass()
 {
     this._spinLock = new SpinLock();
 }
コード例 #26
0
ファイル: SpinLock.cs プロジェクト: tralivali1234/IL2JS
 /// <summary>
 /// SystemThreading_SpinLockDebugView constructor
 /// </summary>
 /// <param name="spinLock">The SpinLock to be proxied.</param>
 public SystemThreading_SpinLockDebugView(SpinLock spinLock)
 {
     // Note that this makes a copy of the SpinLock (struct). It doesn't hold a reference to it.
     m_spinLock = spinLock;
 }
コード例 #27
0
		public void Setup ()
		{
			sl = new SpinLock (true);
		}
コード例 #28
0
ファイル: SpinLockTests.cs プロジェクト: johnhhm/corefx
        public static void RunSpinLockTestExceptions()
        {
            SpinLock slock = new SpinLock();
            bool isTaken = true;
            Assert.Throws<ArgumentException>(() => slock.Enter(ref isTaken));
            // Failure Case: Enter didn't throw AE when isTaken is true

            slock = new SpinLock(false);
            Assert.Throws<InvalidOperationException>(() => { bool iHeld = slock.IsHeldByCurrentThread; });
            // Failure Case: IsHeldByCurrentThread didn't throw IOE when the thread tracking is disabled
        }
コード例 #29
0
ファイル: TcpClient.cs プロジェクト: rmc00/gsf
        /// <summary>
        /// Initializes a new instance of the <see cref="TcpClient"/> class.
        /// </summary>
        /// <param name="connectString">Connect string of the <see cref="TcpClient"/>. See <see cref="DefaultConnectionString"/> for format.</param>
        public TcpClient(string connectString)
            : base(TransportProtocol.Tcp, connectString)
        {
            m_sendLock = new SpinLock();
            m_sendQueue = new ConcurrentQueue<TcpClientPayload>();
            m_payloadAware = DefaultPayloadAware;
            m_payloadMarker = Payload.DefaultMarker;
            m_integratedSecurity = DefaultIntegratedSecurity;
            m_allowDualStackSocket = DefaultAllowDualStackSocket;
            m_maxSendQueueSize = DefaultMaxSendQueueSize;
            m_tcpClient = new TransportProvider<Socket>();

            m_connectHandler = (o, args) => ProcessConnect();
            m_sendHandler = (o, args) => ProcessSend();
            m_receivePayloadAwareHandler = (o, args) => ProcessReceivePayloadAware();
            m_receivePayloadUnawareHandler = (o, args) => ProcessReceivePayloadUnaware();
        }
コード例 #30
0
ファイル: SpinLockTests.cs プロジェクト: johnhhm/corefx
        /// <summary>
        /// Test TryEnter invalid cases
        /// </summary>
        /// <returns>True if succeeded, false otherwise</returns>
        private static void RunSpinLockTest3_TryEnter(bool enableThreadIDs)
        {
            Exception exception = null;
            SpinLock slock = new SpinLock(enableThreadIDs);
            bool lockTaken = false;

            #region Recursive lock
            if (enableThreadIDs) // only valid if thread IDs are on
            {
                // Test recursive locks
                slock.Enter(ref lockTaken);
                try
                {
                    if (lockTaken)
                    {
                        bool dummy = false;
                        // reacquire the lock
                        slock.Enter(ref dummy);
                    }
                }
                catch (Exception ex)
                {
                    // LockRecursionException must be thrown
                    exception = ex;
                }
                if (lockTaken)
                {
                    slock.Exit();
                    if (exception == null || exception.GetType() != typeof(LockRecursionException))
                    {
                        Assert.True(false, string.Format("SpinLock.TryEnter() failed, recursive locks without exception"));
                    }
                    if (slock.IsHeldByCurrentThread)
                    {
                        Assert.True(false, string.Format("SpinLock.TryEnter() failed, IsHeld is true after calling Exit"));
                    }
                }
                else
                {
                    Assert.True(false, string.Format("LockRecursionException was not thrown?"));
                }
            }
            #endregion

            #region timeout > int.max
            // Test invalid argument handling, too long timeout
            exception = null;
            try
            {
                lockTaken = false;
                slock.TryEnter(TimeSpan.MaxValue, ref lockTaken);
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            if (exception == null || exception.GetType() != typeof(ArgumentOutOfRangeException))
            {
                Assert.True(false, string.Format(@"SpinLock.TryEnter() failed, timeout.Totalmilliseconds > int.maxValue
                 without throwing ArgumentOutOfRangeException " + exception));
            }
            #endregion

            #region Timeout > int.max
            // Test invalid argument handling, timeout < -1
            exception = null;
            try
            {
                lockTaken = false;
                slock.TryEnter(-2, ref lockTaken);
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            if (exception == null || exception.GetType() != typeof(ArgumentOutOfRangeException))
            {
                Assert.True(false, string.Format(@"SpinLock.TryEnter() failed, timeout < -1
                 without throwing ArgumentOutOfRangeException"));
            }
            #endregion
        }
コード例 #31
0
ファイル: SpinLockTests.cs プロジェクト: johnhhm/corefx
        /// <summary>
        /// Test Exit
        /// </summary>
        /// <returns>True if succeeded, false otherwise</returns>
        private static void RunSpinLockTest4_Exit(bool enableThreadIDs)
        {
            Exception exception = null;
            SpinLock slock = new SpinLock(enableThreadIDs);
            bool lockTaken = false;
            slock.Enter(ref lockTaken);
            slock.Exit();
            if (enableThreadIDs)
            {
                if (slock.IsHeldByCurrentThread)
                {
                    Assert.True(false, string.Format("SpinLock.Exit() failed, IsHeld is true after calling Exit"));
                }
            }
            else
            {
                if (slock.IsHeld)
                {
                    Assert.True(false, string.Format("SpinLock.Exit() failed, IsHeld is true after calling Exit"));
                }
            }

            for (int i = 0; i < 2; i++)
            {
                bool useBarrier = i == 0;
                // Calling Exit without owning the lock
                try
                {
                    slock.Exit(useBarrier);
                }
                catch (Exception ex)
                {
                    // SynchronizationLockException must be thrown
                    exception = ex;
                }
            }
            if (enableThreadIDs)
            {
                if (exception == null || exception.GetType() != typeof(SynchronizationLockException))
                {
                    Assert.True(false, string.Format(@"SpinLock.Exit() failed, calling Exit without owning the lock"));
                }
            }
        }
コード例 #32
0
ファイル: SpinLockTests.cs プロジェクト: johnhhm/corefx
        /// <summary>
        /// Test SpinLock.TryEnter() by launching n threads, each one calls TryEnter, the succeeded threads increment
        /// a counter variable and failed threads increment failed variable, count + failed must be equal to n
        /// </summary>
        /// <param name="threadsCount">Number of threads that call enter/exit</param>
        /// <returns>True if succeeded, false otherwise</returns>
        private static void RunSpinLockTest1_TryEnter(int threadsCount, bool enableThreadIDs)
        {
            for (int j = 0; j < 2; j++)
            {
                bool useMemoryBarrier = j == 0;
                Task[] threads = new Task[threadsCount];
                SpinLock slock = new SpinLock(enableThreadIDs);
                int succeeded = 0;
                int failed = 0;


                // Run threads
                for (int i = 0; i < threadsCount; i++)
                {
                    threads[i] = Task.Run(delegate ()
                    {
                        bool lockTaken = false;
                        slock.TryEnter(ref lockTaken);
                        if (lockTaken)
                        {
                            // Increment succeeded counter 
                            Interlocked.Increment(ref succeeded);
                            slock.Exit(useMemoryBarrier);
                        }
                        else
                        {
                            // Increment failed counter
                            Interlocked.Increment(ref failed);
                        }
                    });
                }
                // Wait all threads
                for (int i = 0; i < threadsCount; i++)
                {
                    threads[i].Wait();
                }
                // succeeded + failed must be equal to the threads count.
                if (succeeded + failed != threadsCount)
                {
                    Assert.True(false, string.Format("SpinLock.TryEnter() failed, actual count: " + (succeeded + failed) +
                        " expected :" + threadsCount));
                }
            }
        }
コード例 #33
0
ファイル: SpinLockTests.cs プロジェクト: johnhhm/corefx
        /// <summary>
        /// Test SpinLock.TryEnter(Timespan) by generating random timespan milliseconds
        /// </summary>
        /// <param name="threadsCount">Number of threads that call enter/exit</param>
        /// <returns>True if succeeded, false otherwise</returns>
        private static void RunSpinLockTest2_TryEnter(int threadsCount, bool enableThreadIDs)
        {
            for (int j = 0; j < 2; j++)
            {
                bool useMemoryBarrier = j == 0;
                Task[] threads = new Task[threadsCount];
                SpinLock slock = new SpinLock(enableThreadIDs);
                int succeeded = 0;
                int failed = 0;

                // Run threads
                for (int i = 0; i < threadsCount; i++)
                {
                    threads[i] = new Task(delegate (object x)
                    {
                        // Generate random timespan
                        bool lockTaken = false;
                        TimeSpan time = TimeSpan.FromMilliseconds(20);
                        slock.TryEnter(time, ref lockTaken);
                        if (lockTaken)
                        {
                            // add some delay in the critical section
                            Task.WaitAll(Task.Delay(15));
                            Interlocked.Increment(ref succeeded);
                            slock.Exit(useMemoryBarrier);
                        }
                        else
                        {
                            // Failed to get the lock within the timeout
                            Interlocked.Increment(ref failed);
                        }
                    }, i);
                    threads[i].Start(TaskScheduler.Default);
                }
                // Wait all threads
                for (int i = 0; i < threadsCount; i++)
                {
                    threads[i].Wait();
                }
                // succeeded + failed must be equal to the threads count.
                if (succeeded + failed != threadsCount)
                {
                    Assert.True(false, string.Format("SpinLock.TryEnter() failed, actual count: " + (succeeded + failed) +
                        " expected :" + threadsCount));
                }
            }
        }
コード例 #34
0
ファイル: SpinLockTests.cs プロジェクト: johnhhm/corefx
        /// <summary>
        /// Test SpinLock.Enter by launching n threads that increment a variable inside a critical section
        /// the final count variable must be equal to n
        /// </summary>
        /// <param name="threadsCount">Number of threads that call enter/exit</param>
        /// <returns>True if succeeded, false otherwise</returns>
        private static void RunSpinLockTest0_Enter(int threadsCount, bool enableThreadIDs)
        {
            // threads array
            Task[] threads = new Task[threadsCount];
            //spinlock object
            SpinLock slock = new SpinLock(enableThreadIDs);
            // succeeded threads counter
            int succeeded = 0;
            // Semaphore used to make sure that there is no other threads in the critical section
            SemaphoreSlim semaphore = new SemaphoreSlim(1, 1);

            for (int i = 0; i < threadsCount; i++)
            {
                threads[i] = Task.Run(delegate ()
                {
                    bool lockTaken = false;
                    try
                    {
                        slock.Enter(ref lockTaken);
                        //use semaphore to make sure that no other thread inside the critical section
                        if (!semaphore.Wait(0))
                        {
                            // This mean that there is another thread in the critical section
                            return;
                        }
                        succeeded++;
                        if (slock.IsThreadOwnerTrackingEnabled && !slock.IsHeldByCurrentThread)
                        {
                            // lock is obtained successfully
                            succeeded--;
                        }
                    }
                    catch
                    {
                        // decrement the count in case of exception
                        succeeded--;
                    }
                    finally
                    {
                        semaphore.Release();
                        if (lockTaken)
                        {
                            slock.Exit();
                        }
                    }
                });
            }
            // wait all threads
            for (int i = 0; i < threadsCount; i++)
            {
                threads[i].Wait();
            }
            // count must be equal to the threads count
            if (succeeded != threadsCount)
            {
                Assert.True(false, string.Format("SpinLock.Enter() failed, actual count: " + succeeded + " expected: " + threadsCount));
            }
        }
コード例 #35
0
        public void DebuggerProxy_FrameworkTypes_SpinLock()
        {
            var obj = new SpinLock();

            var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline);
            Assert.Equal("SpinLock(IsHeld = false) { IsHeld=false, IsHeldByCurrentThread=false, OwnerThreadID=0 }", str);

            str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList);
            AssertMembers(str, "SpinLock(IsHeld = false)",
                "IsHeld: false",
                "IsHeldByCurrentThread: false",
                "OwnerThreadID: 0"
            );
        }
コード例 #36
0
        private void createCache()
        {
            // Detect all vectors which are being shared along the machines
            var shared = new Dictionary<double[], List<Tuple<int, int, int>>>();

            for (int i = 0; i < machines.Length; i++)
            {
                for (int j = 0; j < machines[i].Length; j++)
                {
                    if (machines[i][j].SupportVectors != null)
                    {
                        for (int k = 0; k < machines[i][j].SupportVectors.Length; k++)
                        {
                            double[] sv = machines[i][j].SupportVectors[k];

                            List<Tuple<int, int, int>> count;
                            bool success = shared.TryGetValue(sv, out count);

                            if (success)
                            {
                                // Value is already in the dictionary
                                count.Add(Tuple.Create(i, j, k));
                            }
                            else
                            {
                                count = new List<Tuple<int, int, int>>();
                                count.Add(Tuple.Create(i, j, k));
                                shared[sv] = count;
                            }
                        }
                    }
                }
            }

            // Create a cache for the shared values
            sharedVectorCache = new double[shared.Count];
            for (int i = 0; i < sharedVectorCache.Length; i++)
                sharedVectorCache[i] = Double.NaN;

            // Create a table of indices for shared vectors
            int idx = 0;

            var indices = new Dictionary<double[], int>();
            foreach (double[] sv in shared.Keys)
                indices[sv] = idx++;

            // Create a lookup table for the machines
            sharedVectors = new int[machines.Length][][];
            for (int i = 0; i < sharedVectors.Length; i++)
            {
                sharedVectors[i] = new int[machines[i].Length][];
                for (int j = 0; j < sharedVectors[i].Length; j++)
                {
                    if (machines[i][j].SupportVectors != null)
                    {
                        sharedVectors[i][j] = new int[machines[i][j].SupportVectors.Length];

                        for (int k = 0; k < machines[i][j].SupportVectors.Length; k++)
                        {
                            double[] sv = machines[i][j].SupportVectors[k];
                            if (shared.ContainsKey(sv))
                                sharedVectors[i][j][k] = indices[sv];
                            else
                                sharedVectors[i][j][k] = -1;
                        }
                    }
                }
            }

            // Create synchronization objects
            syncObjects = new SpinLock[shared.Count];
            for (int i = 0; i < syncObjects.Length; i++)
                syncObjects[i] = new SpinLock();
        }
コード例 #37
-1
ファイル: SpinLockTests.cs プロジェクト: johnhhm/corefx
        public static void EnterExit()
        {
            var sl = new SpinLock();
            Assert.True(sl.IsThreadOwnerTrackingEnabled);

            for (int i = 0; i < 4; i++)
            {
                Assert.False(sl.IsHeld);
                Assert.False(sl.IsHeldByCurrentThread);

                bool lockTaken = false;
                if (i % 2 == 0)
                    sl.Enter(ref lockTaken);
                else
                    sl.TryEnter(ref lockTaken);
                Assert.True(lockTaken);
                Assert.True(sl.IsHeld);
                Assert.True(sl.IsHeldByCurrentThread);
                Task.Factory.StartNew(() =>
                {
                    Assert.True(sl.IsHeld);
                    Assert.False(sl.IsHeldByCurrentThread);
                }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).GetAwaiter().GetResult();
                sl.Exit();
            }
        }
コード例 #38
-1
ファイル: RwLock.cs プロジェクト: dilkaraja94/Homework-3
 public RwLock()
 {
     _numReaders = 0;
     _numWriters = 0;
     _waitingWriters = 0;
     _lock = new SpinLock();
 }