C # multi-thread Technical Summary (synchronization ),

Source: Internet
Author: User

C # multi-thread Technical Summary (synchronization ),

Ii. Serial (synchronous ):

1. lock and Monitor -- note that the locked object must be of the reference type (except string type)

Example:

Private static object syncObject = new object (); private static void TaskWork (object I) {Console. writeLine ("I Am a task: {0}", I); lock (syncObject) {Thread. sleep (1, 1000); Console. writeLine ("I Am a task: {0}, Thread ID: {1}", I, Thread. currentThread. managedThreadId);} try {Monitor. enter (syncObject); Console. writeLine ("I Am a task: {0}, Thread ID: {1}", I, Thread. currentThread. managedThreadId);} finally {Monitor. exit (syncObject) ;}// call a Task. factory. startNew (TaskWork, 1); Task. factory. startNew (TaskWork, 2 );

2. Interlocked

Example:

Int I = 1; Interlocked. increment (ref I); // Increment + 1 = 2; Console. writeLine ("I current value: {0}", I); Interlocked. decrement (ref I); // reduction-1 = 0; Console. writeLine ("I current value: {0}", I); Interlocked. exchange (ref I, 2); // value = 2; Console. writeLine ("I current value: {0}", I); Interlocked. compareExchange (ref I, 10, 2); // compare the exchange value. When I = 2, I is assigned 10; Console. writeLine ("I current value: {0}", I );

3. Mutex-synchronization between processes or 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 completed! "); M. ReleaseMutex () ;}); var t2 = new Task () =>{ Console. WriteLine (" I am the second Task! "); Mutex m = new Mutex (false," test "); m. WaitOne (); Console. WriteLine (" second task completed! "); M. ReleaseMutex () ;}); t1.Start (); t2.Start ();

4. readerWriterLock and ReaderWriterLockSlim -- if the resource does not obtain the write exclusive permission at a certain time point, you can obtain multiple read access permissions and the exclusive permission for a single write, if the write exclusive permission has been obtained at a certain time point, other read access permissions 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. managedThreadId); rwLock. acquireReaderLock (Timeout. infinite); // wait for an indefinite period. You need to explicitly call ReleaseReaderLock to release the lock var readList = state as IEnumerable <int>; foreach (int item in readList) {Console. writeLine ("read current value: {0}", item); Thread. sleep (500);} Console. writeLine ("read completed, Thread ID: {0}", Thread. currentThread. managedThreadId); rwLock. releaseReaderLock ();} static void Write (object state) {Console. writeLine ("I Am a write Thread, Thread ID is: {0}", Thread. currentThread. managedThreadId); rwLock. acquireWriterLock (Timeout. infinite); // wait for an indefinite period. You need to explicitly call ReleaseWriterLock to release the 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: {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 -- ensure that an instance of A class can only be accessed by one thread at A time. The class definition requirement is as follows:. the SynchronizationAttribute attribute must be marked on the 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;} public void WithDraw (string name, object money) {if (int) money <= _ balance) {Thread. sleep (2000); _ balance = _ balance-(int) money; Console. writeLine ("{0} retrieved successfully! Balance = {1} ", name, _ balance);} else {Console. WriteLine (" {0} failed to get the money! Insufficient balance! ", Name) ;}}// call: var account = new Account (); Parallel. invoke () => {account. withDraw ("Zhang San", 600) ;}, () =>{ account. withDraw ("Li Si", 600 );});

6. MethodImplAttribute -- lock the entire method and release the lock until the method returns.

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} retrieved successfully! Balance = {1} ", name, _ balance);} else {Console. WriteLine (" {0} failed to get the money! Insufficient balance! ", Name) ;}}// call var account = new Account (); Parallel. invoke () => {account. withDraw ("Zhang San", 600) ;}, () =>{ account. withDraw ("Li Si", 600 );});

7. AutoResetEvent, ManualResetEvent, and ManualResetEventSlim -- call WaitOne, WaitAny, or WaitAll to wait for the thread to wait for the event. Call the Set Method to send a signal. The event changes to the terminated state and the waiting thread is awakened.

Example:

AutoResetEvent arEvent = new AutoResetEvent (false); // The default value is "no signal" and the Task is in a non-terminating State. factory. startNew (o) =>{ for (int I = 1; I <= 10; I ++) {Console. writeLine ("{0} loop Times", I);} arEvent. set (); // sends a signal, in the terminated state}, arEvent); arEvent. waitOne (); // wait for the signal. After receiving the signal, continue the following execution Console. writeLine ("I am the main thread, and I will continue to execute! "); Console. Read ();

8. Sempaphore and SemaphoreSlim (not cross-process)-semaphores to synchronize threads and processes

Example:

Public class guest room {private readonly Semaphore sem; public guest room (int maxUseableCount) {sem = new Semaphore (maxUseableCount, maxUseableCount, "WC");} public void Use (int I) {Task. factory. startNew () => {Console. writeLine ("{0} individuals waiting to enter", I); // WaitOne. waitOne (); Console. writeLine ("number {0} entered successfully, in use", I); // The simulated Thread executes some operations. sleep (1, 100); Console. writeLine ("{0} individual used up, left", I); // Release: Release a "empty" sem. release () ;}}}// call: var wc = new living room (5); for (int I = 1; I <= 7; I ++) {wc. use (I );}

9. barrier-Barrier enables multiple tasks to work collaboratively in multiple stages in parallel based on an algorithm. That is, tasks in one stage are divided into multiple threads for asynchronous execution, after the execution is completed, the system enters the next stage.

Example:

Int taskSize = 5; Barrier barrier = new Barrier (taskSize, (B) => {Console. writeLine (string. format ("{0} Current Stage Number: {1} {0 }","-". padRight (15, '-'), B. currentPhaseNumber) ;}); var tasks = new Task [taskSize]; for (int I = 0; I <taskSize; I ++) {tasks [I] = Task. factory. startNew (n) => {Console. writeLine ("Task: # {0} ----> processes the first data. ", N); barrier. SignalAndWait (); Console. WriteLine (" Task: # {0} ----> process the second part of the data. ", N); barrier. SignalAndWait (); Console. WriteLine (" Task: # {0} ----> process the third part of the data. ", N); barrier. SignalAndWait () ;}, I) ;}task. WaitAll (tasks );

10. SpinLock -- spin lock, limited to a short lock Period

Example:

SpinLock sLock = new SpinLock (); int num = 0; Action action = () => {bool lockTaken = false; for (int I = 0; I <10; 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 {// release if (lockTaken) sLock. exit () ;}}; // multithreading call: Parallel. invoke (action, action, action); Console. writeLine ("Total: {0}", num );

11. SpinWait -- spin wait, lightweight

Thread. sleep (1000); // The thread waits for 1 S; Console. writeLine (DateTime. now. toString ("yyyy-MM-dd HH: mm: ss. fff "); SpinWait. spinUntil () => false, 1000); // spin wait 1 S Console. writeLine (DateTime. now. toString ("yyyy-MM-dd HH: mm: ss. fff "); Thread. spinWait (100000); // specifies the number of CPU cycles, which are executed at intervals at the processing speed. Generally, Console is not recommended. writeLine (DateTime. now. toString ("yyyy-MM-dd HH: mm: ss. fff "));

12. CountdownEvent -- similar to Sempaphore, but CountdownEvent supports dynamic adjustment of signal count

Example:

Static void TimeLimitShopping (int custCount, int times, CountdownEvent countdown) {var customers = Enumerable. range (1, custCount); foreach (var customer in mers) {int currentCustomer = customer; Task. factory. startNew () => {SpinWait. spinUntil () => false, 1000); Console. writeLine ("No. {0} Customer purchases: 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 (10, 2, countdown); countdown. wait (); countdown. reset (20); TimeLimitShopping (20, 3, countdown); countdown. wait ();

Finally, we will share several Concurrent collection classes in the namespace System. Collections. Concurrent:

ConcurrentBag <T>: indicates an unordered set of thread security;

ConcurrentDictionary <T>: a set of multiple key-value pairs that are thread-safe;

ConcurrentQueue <T>: indicates the first-in-first-out set of thread security;

ConcurrentStack <T>: indicates the post-import, first-out set of thread security;

Several States of the thread (in slices from this article: http://www.cnblogs.com/edisonchou/p/4848131.html ):

Refer to the following articles:

Summary: several methods of C # Thread Synchronization

C # programming Summary (3) thread synchronization

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.