C # Multithreading Learning Summary "1"

Source: Internet
Author: User

(Transferred from Bole online)

I. Related Concepts (http://blog.jobbole.com/92458/)

The code area is shared between different threads. So you can perform the same function =>so, you need lock, something like lock. Or else it's going to be messed up.

Disadvantages:

    • Threads are also programs, so threads need to consume memory, and more threads consume more memory;
    • Multithreading requires coordination and management, so CPU time is required to track threads;
    • Access to shared resources between threads affects each other, and the issue of competing shared resources must be resolved;
    • Too many threads can lead to too much control and can eventually cause many bugs;

Second, thread entry

After Thread.Start, you start executing a delegate: ThreadStart.

//ThreadTest.cs using System; using System.Threading; namespace ThreadTest {    public class Alpha   {        public void Beta()       {          while ( true )         {           Console.WriteLine( "Alpha.Beta is running in its own thread." );         }       }   };    public class Simple   {        public static int Main()       {         Console.WriteLine( "Thread Start/Stop/Join Sample" );              Alpha oAlpha = new Alpha();          //这里创建一个线程,使之执行Alpha类的Beta()方法         Thread oThread = new Thread( new ThreadStart(oAlpha.Beta));         oThread.Start();          while (!oThread.IsAlive)          Thread.Sleep(1);         oThread.Abort();         oThread.Join();         Console.WriteLine();         Console.WriteLine( "Alpha.Beta has finished" );          try         {           Console.WriteLine( "Try to restart the Alpha.Beta thread" );           oThread.Start();         }          catch (ThreadStateException)         {           Console.Write( "ThreadStateException trying to restart Alpha.Beta. " );           Console.WriteLine( "Expected since aborted threads cannot be restarted." );           Console.ReadLine();         }          return 0;       }   } }= = After parsing the ================================================================= main function, instantiate an Alpha class. Open a new thread (one in addition to the main thread), pointing to the beta method of Alpha. Thread is turned on. = = But this is not necessarily the case when the program enters Beta. opening a thread does not mean that the content within this thread has started to work. So let the main thread sleep for 1 seconds. The main thread goes to sleep, and this second ensures that the Beta method is started. The program starts to print the beta sentence. Thread termination. join is waiting for the beta thread to finish before the main thread can continue to run down. Handle other related exceptions. The ====================================================================== corresponds to two lines, and the CPU switches between the two lines of work. The code above does not guarantee that the beta thread will be able to grab the CPU after it starts, so let the main thread wait to make sure the CPU is assigned to the beta thread. Third, Lock,monitor, (http://blog.jobbole.com/92507/) C # provides a keyword LOCK that defines a piece of code as a mutex (critical section), The mutex only allows one thread to go into execution at a time, while other threads must wait. In C #, the keyword lock is defined as follows:

Lock (expression) Statement_block

Expression represents the object that you want to track, usually an object reference.

    • If you want to protect an instance of a class, generally, you can use this;
    • If you want to protect a static variable (such as a mutex snippet inside a static method), you can use the class name in general.

The Monitor class locks an object

When multiple threads are common to an object, there are similar problems with common code, and the lock keyword should not be used. Here we need to use a class monitor in System.Threading, which we can call a monitor, which provides a scenario for threads to share resources.

The Monitor class can lock an object, and a thread can manipulate the object only if it gets the lock. The object lock mechanism ensures that only one thread can access the object at a time when it can cause confusion.
Monitor must be associated with a specific object, but since it is a static class, it cannot be used to define an object, and all its methods are static and cannot be referenced using objects. The following code illustrates the case of locking an object using monitor:

1234 Queue oQueue=newQueue();Monitor.Enter(oQueue);//现在oQueue对象只能被当前线程操纵了Monitor.Exit(oQueue);//释放锁

As shown above, when a thread calls the Monitor.Enter () method to lock an object, the object is owned by it, and the other thread wants to access the object, only to wait for it to release the lock using the Monitor.Exit () method. to ensure that the thread eventually releases the lock, you can write the Monitor.Exit () method in the finally code block in the try-catch-finally structure.

For any object that is locked by monitor, some information about it is stored in memory:

    • One is a reference to the thread that now holds the lock;
    • The second is a reserve column in which the thread that is ready to acquire the lock is saved in the queue;
    • The third is a wait queue, which holds a reference to the queue that is currently waiting for the state of the object to change.

When the thread that owns the lock is ready to release the lock, it uses the Monitor.pulse () method to notify the first thread in the wait queue, and the thread is transferred to the preliminary queue, and the thread in the prestaged queue can get the object lock immediately when the object lock is freed.

"Not finished. The rest of the text has not been read. Read it and write again. 】

C # Multithreading Learning Summary "1"

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.