C # thread synchronization code

#define CODE1

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SomeDemo
{
    public class AsyncDemo
    {
        public void Run()
        {
            MutexTest();
        }

        /// <summary>
        /// 线程间同步, 可以暂时释放锁
        ///TryEnter, Enter to acquire the lock
         /// Exit for releasing the lock
         /// the Wait for provisional release lock, so that other thread acquires the lock
         /// Pulse to threads in a wait state wake
         /// Lock (obj) { {...} is equivalent to the Monitor.Enter the try (obj, token REF); the finally {...} IF (token) the Monitor.Exit (obj);}
         ///  </ Summary> 
        Private  void MonitorTest () 
        { 
            var LCK = new new  Object ();
             var token = to false ;
             var T1 = Task.Run (() => 
            { 
                the Output ( " . 1 Start " );
                Monitor.TryEnter(lck, 500, ref token);
                if (token)
                {
                    Output("1 Enter");
                    Thread.Sleep(3000);
                    Monitor.Wait(lck);
                    Output("1 wait end");
                    Monitor.Exit(lck);
                }
                else
                    Output("1 Pass");
                Output("1 end");
            });

            Thread.Sleep(100);//为了让t1先获取锁
            Output("2 start");
            lock (lck)
            {
                Output("Enter 2");
                Thread.Sleep(3000);
                Monitor.Pulse(lck);
                Output("2 pulse end");
                Thread.Sleep(3000);
            }
            Output("2 end");
            Task.WaitAll (T1);
        } 

                             {///  <Summary> 
        /// provide atomic variables shared by multiple threads
         /// to change, plus or minus operator reminder atomic
         ///  </ Summary> 
        Private  void InterLockedTest () 
        { 
#if CODE1
             // count Demo 
            int CNT = 0 ;
             var TT1 = new new the Task (() => 
            { 
                for ( int I = 0 ; I < 10000000 ; I ++ )
                     // Lock (the this) 

                    Interlocked.Increment ( REF cnt);
                        //cnt += 1;
                    }
            });
            var tt2 = new Task(() =>
            {
                for (int i = 0; i < 10000000; i++)
                    //lock(this)
                    {
                    Interlocked.Increment(ref cnt);
                        //cnt += 1;
                    }
            });
            var ms = GetRunTime(() =>
            {
                tt1.Start ();
                tt2.Start();
                Task.WaitAll (TT1, TT2); 
            }); 
            Console.WriteLine (MS + "  " + CNT);
 #else 
            // with interlock guarantee run once 
            int In Flag = 0 ;
             var tasksWithoutInterLocked Enumerable.Range = ( 0 , 1000000 ) .Select (_i => new new the Task (() => 
            { 
                IF ! (In Flag = 0 )
                     return ; 
                the Thread.Sleep ( . 1 ); // simulation time difference 
                    In Flag = . 1 ;
                Console.WriteLine("maybe one");
            })).ToArray();
            foreach (var t in tasksWithoutInterLocked)
                t.Start();
            Task.WaitAll(tasksWithoutInterLocked);
            Console.WriteLine("无InterLocked任务运行结束");

            flag = 0;
            var tasksWithInterLocked = Enumerable.Range(0, 1000000).Select(_i => new Task(() =>
            {
                IF ( 0== Interlocked.Exchange ( REF In Flag, . 1 )) 
                    Console.WriteLine ( " only One " ); 
            .})) the ToArray (); 
            the foreach ( var T in tasksWithInterLocked) 
                t.start (); 
            Task.WaitAll (tasksWithInterLocked ); 
            Console.WriteLine ( " the Interlocked task runs end " );
 #endif 
        } 

        ///  <Summary> 
        /// for signal transmission between the two threads, to ensure that the order of execution between the different threads
         /// the initialState constructor can be understood as a state of the door, true indicates that the door is open, false indicates that the door is closed
         ///Call waitone time if the door is open directly to the door and then automatically closed, if the door is closed and so the state after the door opened into the
         /// calls Set expressed open the door, then the first call waitone thread becomes
         /// call Reset representation closing
         ///  </ Summary> 
        Private  void AutoResetEventTest () 
        { 
            var are = new new the AutoResetEvent ( to true );
             int loopTimes = 100 ;
             var T1 = Task.Run (() => 
            { 
                for ( int I = 0 ; I <loopTimes ; i ++ )  
                {
                    are ? .WaitOne (); 
                    the Output ("1: " + i);
                    Thread.Sleep(1);
                    are?.Set();
                }
            });

            for (int i = 0; i < loopTimes; i++)
            {
                are?.WaitOne();
                Output("----2: " + i);
                Thread.Sleep(1);
                are?.Set (); 
            } 
            Task.WaitAll (T1); 
        }

        ///  <Summary> 
        /// the ManualResetEvent substantially consistent AutoResetEvent
         /// difference is automatically invoked after AutoResetEvent WaitOne Reset, ManualResetEvent Reset to manually call by blocking WaitOne
         ///  </ Summary> 
        Private  void ManualResetEventTest () 
        {} 

        Private  void MethodImplAttributeTest () 
        { 
            var Tasks Enumerable.Range = ( 0 , . 5 ) .Select (_i => new new the Task (FuncWithMethidImpl)) the ToArray ();.
             the foreach ( var T in Tasks) 
                t.start ();
            Task.WaitAll (Tasks); 
        } 

        ///  <Summary> 
        /// overall process locked
         ///  </ Summary> 
        [the MethodImpl (MethodImplOptions.Synchronized)]
         Private  void FuncWithMethidImpl () 
        { 
            the Output ( "" ); 
            the Thread. SLEEP ( 1000 ); 
        } 

        ///  <Summary> 
        /// write lock
         /// using ReaderWriterLock resource access, and if not acquired exclusive rights written at a certain time of resources, you can gain access to a plurality of read rights, exclusive rights to a single write that, if a certain time has acquired exclusive rights to write, then read other access must wait
         /// AcquireReaderLock / ReleaseReaderLock for application / release read lock
         /// AcquireWriterLock / ReleaseWriterLock 用于申请/释放写锁
        /// </summary>
        private void ReaderWriterLockTest()
        {
            var lck = new ReaderWriterLock();

            var funcRead = new Action(() =>
            {
                lck.AcquireReaderLock(int.MaxValue);
                Output("read lock get");
                Thread.Sleep(2000);
                Output("read lock release");
                lck.ReleaseReaderLock();
            });

            var funcWrite = new Action(() =>
            {
                Thread.Sleep(5);//为了让读锁先获取
                lck.AcquireWriterLock(int.MaxValue);
                Output("write lock get");
                Thread.Sleep(2000);
                Output("write lock release");
                lck.ReleaseWriterLock();
            });

            var tr1 = new Task(funcRead);
            var tr2 = newTask (funcRead);
            var tr3 = new new Task (funcRead);
             var TW1 = new new Task (funcWrite);
             var tw2 = new new Task (funcWrite); 

            // first apply two read lock request two write lock apply for a read lock 
            tr1.Start (); 
            tr2.Start (); 
            tw1.Start (); 
            tw2.Start (); 
            the Thread.Sleep ( 100 ); 
            tr3.Start (); 

            Task.WaitAll (Tr1, Tr2 is, Tr3, TW1, TW2 ); 
        } 

        ///  <Summary> 
        /// mutex, it may be used for inter-process synchronization
         /// constructor unique name in the operating system
         ///WaitOne locking
         /// ReleaseMutex unlocking
         /// WaitOne ReleaseMutex execution times and must be consistent
         ///  </ Summary> 
        Private  void MutexTest () 
        { 
            the using ( var the mutex = new new the Mutex ( to true , " whosyourdaddy " , OUT  BOOL isNew )) 
            { 
                IF (isNew) 
                    Console.WriteLine ( " started successfully, any key to exit " );
                 the else 
                { 
                    Console.WriteLine ( " failed to start, waiting for other programs to quit" ); 
                    Mutex.WaitOne (); 
                    Console.WriteLine ( " started successfully, any key to exit " ); 
                } 
                the Console.ReadKey (); 
                mutex.ReleaseMutex (); 
            } 
        } 

        ///  <Summary> 
        /// semaphore, while the number of operations for controlling access to a particular resource can be used for inter-process synchronization
         /// the WaitOne, Release
         ///  </ Summary> 
        Private  void SemaphoreTest () 
        { 
            the using (SEM = Semaphore new new Semaphore ( . 3 , . 3 , " greedisgood"))
            {
                Console.WriteLine("start");
                sem.WaitOne();
                Console.WriteLine("enter");
                Console.ReadKey();
                sem.Release();
                Console.WriteLine("exit");
            }
        }

        private void Output(string msg)
        {
            Console.WriteLine(DateTime.Now.ToString("mm:ss.fff") + ": " + msg);
        }

        private long GetRunTime(Action action)
        {
            var watch = Stopwatch.StartNew();
            action();
            watch.Stop();
            return watch.ElapsedMilliseconds;
        }
    }
}

Guess you like

Origin www.cnblogs.com/onestow/p/12026509.html