c # thread - Thread Synchronization (halcon forum users to provide)

Thread synchronization 


, if multiple threads simultaneously access shared data, you must use thread synchronization, shared prevent data corruption. If multiple threads do not access the shared data at the same time, you can not thread synchronization. 
Thread synchronization will have some problems:

  1. Performance loss. Acquire, release the lock, thread context switches are built consumption performance.
  2. Thread synchronization will be queued for execution.



Several methods thread synchronization:  



blocked 


when the thread calls Sleep, Join, EndInvoke, the thread is blocked (Sleep the calling thread to block, Join, EndInvoke to make another thread is blocked), will immediately withdraw from cpu. (Blocked state thread does not consume cpu) 
when the thread switching between blocking and non-blocking state consumes a few milliseconds.  
Static void Main the Join // () { 
  the Thread the Thread new new T = (Go); 
  Console.WriteLine ( "Main methods were run ....");   
  t.start (); 
  t.Join (); // Main blocked the method Console.WriteLine ( "Main method of unblocking, continue ..."); 
} static void Go () { 
  Console.WriteLine ( "Go run method on a thread t ..."); 
} // static void at Sleep Main () { 
  Console.WriteLine ( "Main method has been run ....");   
  Thread.CurrentThread.Sleep (3000); // blocks the current thread Console.WriteLine ( "Main method of unblocking, continues to run ..." ); 
} // the Task static void the Main () { 
   the Task Task.Run Task1 = (() => {   
            Console.WriteLine ( "task execution method ..."); 
              the Thread.Sleep (1000); 
            }); 
   Console.WriteLine (Task1.IsCompleted);             
   Task1.Wait (); // block the main thread, the other Task1 completion Console .WriteLine (Task1.IsCompleted); 




Lock (lock) 


locking the multiple threads at the same time only one thread can call this method, other threads are blocked. 
Synchronization object selection:

  • Using reference type , boxed value type lock will generate a new object.
  • The use of private modification, easy to produce a deadlock when using public. (Using lock (this), when the lock (typeof (Example)), should be such Private) .
  • As the string can not lock object.
  • You can not use the await keyword lock



Whether the lock must be statically typed?  


If locked method is static, then the lock must be statically typed. Such is the global lock method, no matter how many instances of the class, to be queued for execution. 
If locked in the method is not static, the static type of lock can not be used, because the method is part of the locking instance, so long as the locking method call instance can without damage, different instances of the lock is not required. This lock of the lock is only an example of the method, but not all instances locks methods * 
class the ThreadSafe { 
 Private static Object _locker = new new Object (); 
  
  void Go () 
  {Lock (_locker) 
    { 
      ...... // shared operational data (static method), using a static instance locks to ensure that all queued execution} 
  } private object _locker2 = new object (shared data operations, non-static method is non- the method of static lock, to ensure that the same instance of the caller queued execution} 


synchronization objects may serve as objects that lock on 
as: 
class the ThreadSafe { 
 Private List <String> the _list = new new List <String> (); 
  void the Test () 
  { 
    lock ( the _list) 
    { 
      _list.Add ( "Item 1"); 
    } 
  } 



Monitors 


Lock fact Monitors concise wording. 
Lock (X)   
{   
    the DoSomething ();   


There is actually the same. 
Obj = System.Object (System.Object) X;   
System.Threading.Monitor.Enter (obj); the try {   
    the DoSomething ();   
} {the finally   
    System.Threading.Monitor.Exit (obj);   




Mutex (Mutex) 


mutex is a synchronization object mutually exclusive, at the same time and only one thread can get it. Synchronization can be achieved on process-level threads. 
class Program {// instantiate a mutex lock the mutex the Mutex = new new static public the Mutex (); static void the Main (String [] args) {for (int I = 0; I <. 3; I ++) 
            {// different the method calls the thread mutex protected by the thread new new = Test the thread (MutexMethod); 
                test.Start (); 
            } 
            Console.Read (); 
        } public static void MutexMethod () { 
           Console.WriteLine ( "{0} request mutex ", Thread.CurrentThread.Name); 
           mut.WaitOne (); 
           Console.WriteLine (" {0} has been acquired mutex ", Thread.CurrentThread.Name);     
           the Thread.Sleep (1000); 
           Console. WriteLine ( "{0} ready to release the mutex", Thread.CurrentThread.Name); // release the mutex mut.ReleaseMutex (); 
           Console.WriteLine ( "{0} has been released mutex", Thread.CurrentThread.Name); 
        } 
    } 

mutex can implement thread synchronization between different processes 
using a mutex can only achieve a start of an application Features. 
 public static class SingleInstance {private static Mutex m; public static bool IsSingleInstance () {// create a need for the application to false = isCreateNew Boolean; the try { 
               m = the Mutex new new (initiallyOwned: to true, name: "SingleInstanceMutex", createdNew: OUT isCreateNew ); 
            } the catch (Exception EX) 
            { 
               
            } return isCreateNew; 
        } 
    } 

constructor takes three arguments mutex


  1. initiallyOwned: initiallyOwned If true, the initial state of the mutex is to be acquired by instantiating a thread, the thread is instantiated otherwise not get the status.

  2. name: the name mutex, only one operating system named mutex mutex name, if a thread gets the name of the mutex, other threads can not get the mutex, and must wait for that thread the release of this thread.

  3. createNew: If the mutex with the specified name already exists returns false, true otherwise.



Signals and handle 


lock and mutex can implement thread synchronization, ensure that only one thread of execution. But the communication between threads can not be achieved. If a thread need to communicate, then we must use AutoResetEvent, ManualResetEvent, communicate with each other through signal. They have two states, final states and non-terminating state. Only in a non-termination state, the thread can only be blocked. 

AutoResetEvent: 


AutoResetEvent constructor can pass a parameter of type bool, false indicates the initial state of the object to AutoResetEvent nonsignaled. If the final state is true identities, WaitOne method will not clog up the thread. But because the class will terminate automatically modify the state of the non-termination, so, after then call WaitOne method will be blocked. 
WaitOne method if AutoResetEvent object state non-termination, the thread of the method of blocking calls. You can specify the time, if no response is received signal, returns false 
the SET method to release the blocked thread. But one can only release a blocked thread. 
class ThreadSafe {static AutoResetEvent autoEvent; staticmake AutoResetEvent termination state in a non-new new AutoResetEvent = autoEvent (to false);   

        Console.WriteLine ( "main thread to run ...");   
        the Thread the Thread new new T = (the DoWork );   
        t.start ();   

        Console.WriteLine ( "main thread sleep 1 seconds ...");   
        The Thread.Sleep (1000);   

        Console.WriteLine ( "main thread release signal ...");   
        autoEvent.Set ();   
    } static void DoWork () {   
        Console.WriteLine ( "T thread running DoWork method, blocks its main waiting thread signal ... ");   
        autoEvent.WaitOne ();   
        Console.WriteLine (" T method DoWork thread to the main thread acquired the signal, to continue ... ");   
    }   

} // // output main thread running ... // main thread sleep 1 Miao ... // t thread running DoWork method, blocks its main thread to wait for the signal to release the main thread ... // ... // t signal thread DoWork method to get to the main thread signals continue ... 


ManualResetEvent 


ManualResetEvent and AutoResetEvent similar usage. 
AutoResetEvent after calling the Set method will automatically signal the release (termination) was changed to blocking (non-terminating), only one thread will be released signal. And ManualResetEvent after calling the Set method does not automatically signal the release (termination) was changed to blocking (non-terminating), but has maintained a release signal, so that there is more than one blocked thread to run only manually call the Reset method the signal from the release (termination) was changed to blocking (non-terminating), after then call Wait.One method thread will be blocked again. 
public class ThreadSafe {// create ManualResetEvent private static ManualResetEvent mre a in a non-terminating state = new new the ManualResetEvent (to false); static void the Main () {for (int I = 0; I <= 2; I ++) 
        { 
            the Thread T = new new the thread (the ThreadProc); 
            t.Name = "Thread_" + I; 
            t.start (); 
        } 

        the Thread.Sleep (500); 
        Console.WriteLine ( "\ n the new method the thread has been started, and is blocked, the call is released Set Stuck thread "); 

        mre.Set (); 

        Thread.Sleep (500); 
        Console.WriteLine (" \ when the n-ManualResetEvent in the termination of state, called by multiple threads Wait.One method, will not be blocked "); for (int I =. 3; I <=. 4; I ++) 
        { 
            the Thread the Thread new new T = (the ThreadProc); 
            t.Name = "Thread_" + I;  
            t.Start(); 
        } 

        The Thread.Sleep (500); 
        Console.WriteLine ( "\ n-Reset method is called, the ManualResetEvent unblocked state, then the method call Wait.One thread is blocked again"); 
   

        reset it to (); 

        the Thread T5 = new new the thread (ThreadProc); 
        t5.Name = "Thread_5"; 
        t5.Start (); 

        Thread.Sleep (500); 
        Console.WriteLine ( "\ Set the n-call method, the release of blocked thread"); 

        mre.Set (); 
    } static void the ThreadProc Private () {String name = Thread.CurrentThread.Name; 

        Console.WriteLine (name + "and invokes the WaitOne ()"); 

        mre.WaitOne (); 

        Console.WriteLine (name + "end"); 
    } 
} // Thread_2 run and call WaitOne () // Thread_1 run and call WaitOne () // Thread_0 run and call WaitOne () // method of the new thread has been started and blocked calls Set to release blocked thread // Thread_2 end // end // thread_1 end Thread_0 // when ManualResetEvent in the termination of state, called by multiple threads Wait.One method will not be blocked. // Thread_3 run and call WaitOne () // Thread_4 run and call WaitOne () // Thread_4 end // Thread_3 end /// Reset method is called, ManualResetEvent unblocked, this time calling Wait.One to the thread again // Thread_5 run blocking and call WaitOne () // call the Set method, the release of blocked thread // Thread_5 end 




Interlocked 


if a variable is modified by multiple threads to read. You can use Interlocked. 
Deletions can not be guaranteed to a computer data are atomic, since the operation of the data is sub-steps of:

  1. The value of the instance variable is loaded into the registers.
  2. Increase or decrease the value.
  3. This value is stored in the instance variables.


Interlocked provides atomic operations to multi-threaded shared variables. 
Interlocked provides methods require the atomic operation:

  • public static int Add (ref int location1, int value); two parameters are added, and the result of the first parameter and assignment.
  • public static int Increment (ref int location); 自增。

  • public static int CompareExchange (ref int location1  , int value, int comparand);
    and comparand LOCATION1 comparison, value been replaced. 
    value if the first parameter and the third parameter is equal, then put a value assigned to the first parameter. 
    Comparative comparand and the first parameter.



ReaderWriterLock 


If you want to make sure that a resource or data is up to date before being accessed. Then you can use ReaderWriterLock. The lock ensures that when resources get an assignment or update, it is only they can access these resources, other threads can not access. That exclusive lock. However, when reading the data change lock, an exclusive lock can not be achieved. 
lock allows only one thread executes the same time. The ReaderWriterLock allows the same time there are multiple threads can perform a read operation , or there is only one thread of execution platoon lock the write operation
 class Program {// create an object public static ReaderWriterLock readerwritelock = new ReaderWriterLock (Create a thread reads data Thread t1 = new Thread (Write)(1); thread t2 = newCreate a thread 10 reads data for (int I =. 3; I <. 6; I ++) 
            { 
                the thread new new T = the thread (the Read); // t.start (I);} 

            Console.Read (); 

        } // writing method public static void Write (object i) {// Get the write lock, 20 msec timeout. Console.WriteLine ( "Thread:" + i + "going to write ..."); 
            readerwritelock.AcquireWriterLock (Timeout.Infinite); 
            Console.WriteLine ( "Thread:" + i + "write" + DateTime.Now); // release write lock Console.WriteLine ( "thread:" + i + "write end ..."); 
            Thread.Sleep (1000); 
            readerwritelock.ReleaseWriterLock (); 

        } // read method public static void read ( I Object) { 
            Console.WriteLine ( "thread:" + i + "read ready ..."); // acquire the read lock, 20 msec timeout readerwritelock.AcquireReaderLock (Timeout.Infinite); 
            Console.WriteLine ( "thread: "+ i +" read "+ DateTime.Now); // read lock release Console.WriteLine (" thread: "+ i +" read end. 


            readerwritelock.ReleaseReaderLock (); 

        } 
    } // reader and writer methods are shielded. You can more clearly see the writer was blocked. The reader is not blocked. // // Methods shield reader threads: 1 ready to write ... // thread: 1 // write 2017/7/5 17:50:01 Thread: End 1 write ... // thread: 2 ready to write. .. // thread: 2 writes 2017/7/5 17:50:02 // thread: 2 write shield end ... // writer // method thread: 3 ready to read ... // thread: 5 preparation read ... // thread: 4 ready to read ... // thread: 5 read 2017/7/5 17:50:54 // thread: 5 read end ... // thread: 3 2017 read / 7/5 17:50:54 // thread: 3 read end ... // thread: 4 reads 2017/7/5 17:50:54 // thread: 4 read end ...

 

Guess you like

Origin www.cnblogs.com/wwwbdabc/p/12297856.html