Second, serial (synchronous):
1.lock, monitor--Note the locked object must be a reference type (except for string types)
Example:
private static Object SyncObject = new Object (); private static void Taskwork (Object i) { Console.WriteLine ("I am the task: {0}", i); Lock (SyncObject) { thread.sleep (+); Console.WriteLine ("I am a task: {0}, Thread id:{1}", I,thread.currentthread.managedthreadid); } Try { monitor.enter (syncobject); Console.WriteLine ("I am the task: {0}, Thread id:{1}", I, Thread.CurrentThread.ManagedThreadId); } Finally { monitor.exit (syncobject); } } Call Task.Factory.StartNew (taskwork,1); Task.Factory.StartNew (Taskwork, 2);
2.Interlocked
Example:
int i=1; Interlocked.Increment (ref i); incremental +1=2; Console.WriteLine ("I Current value: {0}", i); Interlocked.decrement (ref i); Reduce the amount of -1=0; Console.WriteLine ("I Current value: {0}", i); Interlocked.exchange (ref I, 2);//assigned value =2; Console.WriteLine ("I Current value: {0}", i); Interlocked.compareexchange (ref I, 10, 2);//Compare exchange value, when i=2, then I will be assigned to a value of ten; Console.WriteLine ("I Current value: {0}", i);
3.mutex--enables synchronization between processes, even between two remote processes
Example:
var t1 = new Task (() + = { Console.WriteLine ("I am the first task!") "); Mutex m = new Mutex (false, "test"); M.waitone (); Console.WriteLine ("The first task is done!") "); M.releasemutex (); }); var t2 = new Task (() + = { Console.WriteLine ("I am the second task!") "); Mutex m = new Mutex (false, "test"); M.waitone (); Console.WriteLine ("The second task is done!") "); M.releasemutex (); }); T1. Start (); T2. Start ();
4.ReaderWriterLock, readerwriterlockslim--If at some point the resource does not acquire the exclusive right to write, then you can get multiple read access, the exclusive right of a single write, if a moment has acquired the exclusive right to write, Then the other read access must wait.
Example:
static ReaderWriterLock RwLock = new ReaderWriterLock (); static void Read (object state) {Console.WriteLine ("I am a read thread, thread ID is: {0}", Thread.CurrentThread.ManagedThreadI D); Rwlock.acquirereaderlock (timeout.infinite);//wait indefinitely, require an explicit call to Releasereaderlock release lock var readlist = State as Ienumerab le<int>; foreach (int item in readlist) {Console.WriteLine ("read Current value: {0}", item); Thread.Sleep (500); } Console.WriteLine ("Read completed, thread ID is: {0}", Thread.CurrentThread.ManagedThreadId); Rwlock.releasereaderlock (); } static void Write (object state) {Console.WriteLine ("I am a write thread, thread ID is: {0}", Thread.CurrentThread.Man Agedthreadid); Rwlock.acquirewriterlock (Timeout.infinite); Waits indefinitely, requires an explicit call to Releasewriterlock release lock var writelist = State as list<int>; int Lastcount=writelist.count (); for (int i = LastcoUnt I <= 10+lastcount; i++) {writelist.add (i); Console.WriteLine ("Write current value: {0}", i); Thread.Sleep (500); } Console.WriteLine ("Write completed, thread ID is: {0}", Thread.CurrentThread.ManagedThreadId); Rwlock.releasewriterlock (); }//Call: var rwlist = new list<int> (); var T1 = new Thread (Write); var t2 = new Thread (Read); var t3 = new Thread (Write); var t4 = new Thread (Read); T1. Start (rwlist); T2. Start (rwlist); T3. Start (rwlist); T4. Start (rwlist);
5.synchronizationattribute--ensures that instances of a class can only be accessed by one thread at a time. The definition of a class requires: A. SynchronizationAttribute attribute must be marked on A class, B. Class must inherit from System.ContextBoundObject object
Example:
[Synchronization (Synchronizationattribute.required,true)] public class Account:System.ContextBoundObject { private static int _balance; public int Blance {get {return _balance; }} public account () {_balance = 1000; The public void withdraw (string Name,object money) {if ((int.) Money <= _balance) { Thread.Sleep (2000); _balance = _balance-(int) money; Console.WriteLine ("{0}" to take money successfully! Balance ={1} ", name, _balance); } else {Console.WriteLine ("{0} failed to take money! Insufficient balance! ", name); }}}//call: var account = new account (); Parallel.Invoke (() = {account. Withdraw ("Zhang San", 600); }, () = {account. Withdraw ("John Doe", 600); });
6.methodimplattribute--the entire method until the method returns, releasing the lock
Example:
public class Account {private static int _balance; public int Blance {get {return _balance; }} public account () {_balance = 1000; } [MethodImpl (methodimploptions.synchronized)] public void Withdraw (string name,object money) { if ((int) money <= _balance) {thread.sleep (2000); _balance = _balance-(int) money; Console.WriteLine ("{0}" to take money successfully! Balance ={1} ", name, _balance); } else {Console.WriteLine ("{0} failed to take money! Insufficient balance! ", name); }}}//call var account = new account (); Parallel.Invoke (() = {account. Withdraw ("Zhang San", 600); }, () = {account. Withdraw ("John Doe", 600); });
7.AutoResetEvent, ManualResetEvent, manualreseteventslim--call WaitOne, WaitAny, or WaitAll to make the thread wait for the event, call the Set method to send a signal, The event becomes signaled and the waiting thread is awakened
Example:
AutoResetEvent arevent = new AutoResetEvent (false);//default is no signal, in non-terminating state Task.Factory.StartNew ((o) + = {( int i = 1; I <= 10; i++) { Console.WriteLine ("Loop {0} times", i); } Arevent.set ();//Send signal, in the terminating state },arevent); Arevent.waitone ();//wait for the signal, after receiving the signal, proceed to the following execution Console.WriteLine ("I am the main thread, I continue to execute!") "); Console.read ();
8.Sempaphore, Semaphoreslim (non-cross-process)-semaphore, thread, interprocess synchronization
Example:
public class Washroom {private readonly Semaphore sem; Public washroom (int maxuseablecount) {sem = new Semaphore (Maxuseablecount, Maxuseablecount, "WC"); } public void use (int i) {Task.Factory.StartNew () = { Console.WriteLine ("{0} individual waits for entry", I); WaitOne: If there is a "vacancy", then the placeholder, if there is no vacancy, then wait; SEM. WaitOne (); Console.WriteLine ("{0} Personal successful entry, in use", I); The impersonation thread performed some operations Thread.Sleep (100); Console.WriteLine ("The first {0} individuals were exhausted, left", i); Release: Releases an "empty" SEM. Release (); }); }}//call: var WC = new washroom (5); for (int i = 1; I <= 7; i++) {WC. Use (i); }
The 9.barrier--barrier enables multiple tasks to work together in parallel based on an algorithm in a number of phases, namely: dividing a phase into multiple threads, executing asynchronously, and then entering the next stage at the same time
Example:
int tasksize = 5; Barrier Barrier = new Barrier (tasksize, (b) + = { Console.WriteLine (string. Format ("{0} Current stage number: {1}{0}", "-". PadRight (B.currentphasenumber));) ; var tasks = new Task[tasksize]; for (int i = 0; i < tasksize; i++) { Tasks[i] = Task.Factory.StartNew ((n) + = { Console.WriteLine (" Task: #{0} ----> processed the first part of the data. ", n); Barrier. SignalAndWait (); Console.WriteLine ("Task: #{0}" ----> processed the second part of the data. ", n); Barrier. SignalAndWait (); Console.WriteLine ("Task: #{0} ----> processed the third part of the data. ", n); Barrier. SignalAndWait (); }, I); } Task.waitall (tasks);
10.spinlock--spin Lock, short lock-only time
Example:
SpinLock slock = new SpinLock (); int num = 0; Action action = () = { bool LockTaken = false; for (int i = 0; i < i++) { LockTaken = false; Try { slock.enter (ref lockTaken); Console.WriteLine ("{0}+1={1}---thread id:[{2}]", num, ++num,thread.currentthread.managedthreadid); Thread.Sleep (New Random (). Next (9)); } Finally { //After Real acquisition, release if (LockTaken) Slock.exit ();} } };/ /multithreaded Invocation: Parallel.Invoke (Action, Action, action); Console.WriteLine ("Total: {0}", num);
11.spinwait--spin Wait, lightweight
Thread.Sleep (1000);//thread waits 1S; Console.WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss.fff")); Spinwait.spinuntil (() = false, 1000);//spin-wait 1S Console.WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd hh:mm: Ss.fff ")); Thread.spinwait (100000);//Specifies the number of cycles of the CPU, the time interval is executed at the speed of the processor, it is generally not recommended to use Console.WriteLine (DateTime.Now.ToString (" YYYY-MM-DD HH:mm:ss.fff "));
12.countdownevent--is similar to Sempaphore, but countdownevent supports dynamic adjustment of signal counts
Example:
static void timelimitshopping (int custcount,int times,countdownevent countdown) {var customers = Enumerable.range (1, Custcount); foreach (var customer in customers) {int currentcustomer = customer; Task.Factory.StartNew (() = {Spinwait.spinuntil (() = false, 1000); Console.WriteLine ("{0} Wave Customer purchase: customer-{1}-purchased.", Times, Currentcustomer); Countdown. Signal (); }); Countdown. Addcount (); }}//Call: var countdown = new Countdownevent (5); Timelimitshopping (5, 1, Countdown); Countdown. Wait (); Countdown. Reset (10); Timelimitshopping (Ten, 2, Countdown); Countdown. Wait (); Countdown. Reset (20); Timelimitshopping (3, Countdown); Countdown. Wait ();
Finally, share several concurrent collection classes under the System.Collections.Concurrent namespace:
Concurrentbag<t>: An unordered collection that represents thread safety;
Concurrentdictionary<t>: A collection of multiple key-value pairs that represent thread safety;
Concurrentqueue<t>: Represents a thread-safe FIFO collection;
Concurrentstack<t>: Represents a thread-safe LIFO collection;
Several states of the thread (in slices from this article: http://www.cnblogs.com/edisonchou/p/4848131.html):
Refer to the following related articles:
Summarize: Several methods of C # thread synchronization
C # Programming Summary (iii) thread synchronization
C # Multithreading Technology Summary (synchronous)