Description of the lock keyword in C # Multithreading

Source: Internet
Author: User

Description of the lock keyword in C # Multithreading

This article introduces the C # Lock keyword. C # provides a keyword lock, which canCodeIt is defined as a critical section. Only one thread is allowed to enter the execution at a time, and other threads must wait.

Each thread has its own resources, but the code zone is shared, that is, each thread can execute the same function. This may cause several threads to execute a function at the same time, resulting in data confusion and unexpected results. Therefore, we must avoid this situation.

C # provides a keyword lock, which defines a piece of code as a critical section. A mutex section allows only one thread to enter the execution at a time point, other threads must wait. The C # Lock keyword is defined as follows:

Lock (expression) statement_block

Expression indicates the object you want to trace. It is 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 code segment inside a static method ), generally, you can use a class name.

The statement_block is the code of the mutex, which can be executed by only one thread at a time.

The following is a typical example of using the C # Lock keyword. The usage and usage of the C # Lock keyword are described in the annotations.

Example:

Code highlighting produced by actipro codehighlighter (freeware) http:  //  Www.codehighlighter.com/--> using system;  Using  System. Threading;  Namespace  Threadsimple {  Internal   Class  Account {  Int Balance; //  Balance Random r = New Random ();  Internal Account ( Int  Initial) {balance = Initial ;}  Internal   Int Withdraw ( Int Amount) //  Retrieval and withdrawal  {  If (Balance < 0 ){  //  If the balance is less than 0, an exception is thrown.                  Throw   New Exception ( "  Negativebalance  " ); //  Negative balance  }  //  The following code ensures that the balance value is modified by the current thread.  // No other threads will execute this code to modify the balance value.  //  Therefore, the balance value cannot be smaller than 0.              Lock ( This  ) {Console. writeline (  "  Currentthread:  " + Thread. currentthread. Name );  //  If there is no lock keyword protection, it may be after the if condition judgment (true) is executed.  // The other thread executes balance = balance-amount and modifies the balance value.  //  This modification is invisible to this thread, so it may cause the if condition to be invalid.  //  However, this thread continues to execute balance = balance-amount, so the balance may be less than 0                  If (Balance> = Amount) {thread. Sleep (  5  ); Balance = Balance- Amount;  Return  Amount ;} Else  {  Return   0  ;  //  Transactionrejected  }}}  Internal   Void Dotransactions () //  Withdrawal transactions  {  For (Int I = 0 ; I < 100 ; I ++ ) {Withdraw (R. Next ( - 50 , 100  ));}}}  Internal   Class  Test {  Static   Internal Thread [] threads = New Thread [10  ];  Public   Static   Void  Main () {account ACC = New Account ( 0  );  For ( Int I = 0 ; I < 10 ; I ++ ) {Thread t =New Thread ( New  Threadstart (Acc. dotransactions); threads [I] = T ;}  For ( Int I = 0 ; I < 10 ; I ++ ) {Threads [I]. Name = I. tostring ();}  For ( Int I =0 ; I < 10 ; I ++ ) {Threads [I]. Start (); console. Readline ();}}}} 

 

This article introduces the C # Lock keyword. C # provides a keyword lock, which defines a piece of code as a mutex section ), A mutex can only be executed by one thread at a time, while other threads must wait.

Each thread has its own resources, but the code zone is shared, that is, each thread can execute the same function. This may cause several threads to execute a function at the same time, resulting in data confusion and unexpected results. Therefore, we must avoid this situation.

C # provides a keyword lock, which defines a piece of code as a critical section. A mutex section allows only one thread to enter the execution at a time point, other threads must wait. The C # Lock keyword is defined as follows:

Lock (expression) statement_block

Expression indicates the object you want to trace. It is 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 code segment inside a static method ), generally, you can use a class name.

The statement_block is the code of the mutex, which can be executed by only one thread at a time.

The following is a typical example of using the C # Lock keyword. The usage and usage of the C # Lock keyword are described in the annotations.

Example:

 Code highlighting produced by actipro codehighlighter (freeware) http:  //  Www.codehighlighter.com/--> using system;  Using  System. Threading;  Namespace  Threadsimple {  Internal   Class  Account {  Int Balance; //  Balance Random r = New  Random ();  Internal Account ( Int  Initial) {balance = Initial ;}  Internal   Int Withdraw ( Int Amount) //  Retrieval and withdrawal {  If (Balance < 0  ){  //  If the balance is less than 0, an exception is thrown.                  Throw   New Exception ( "  Negativebalance  " ); //  Negative balance  }  // The following code ensures that the balance value is modified by the current thread.  //  No other threads will execute this code to modify the balance value.  //  Therefore, the balance value cannot be smaller than 0.              Lock ( This  ) {Console. writeline (  "  Currentthread:  " + Thread. currentthread. Name );  // If there is no lock keyword protection, it may be after the if condition judgment (true) is executed.  //  The other thread executes balance = balance-amount and modifies the balance value.  //  This modification is invisible to this thread, so it may cause the if condition to be invalid.  //  However, this thread continues to execute balance = balance-amount, so the balance may be less than 0                  If (Balance> = Amount) {thread. Sleep (  5  ); Balance = Balance-Amount;  Return  Amount ;}  Else  {  Return   0  ;  //  Transactionrejected  }}}  Internal   Void Dotransactions () // Withdrawal transactions  {  For ( Int I = 0 ; I < 100 ; I ++ ) {Withdraw (R. Next ( - 50 , 100  ));}}}  Internal   Class  Test {  Static  Internal Thread [] threads = New Thread [ 10  ];  Public   Static   Void  Main () {account ACC = New Account ( 0  );  For ( Int I = 0 ; I <10 ; I ++ ) {Thread t = New Thread ( New  Threadstart (Acc. dotransactions); threads [I] = T ;}  For ( Int I = 0 ; I < 10 ; I ++ ) {Threads [I]. Name =I. tostring ();}  For ( Int I = 0 ; I < 10 ; I ++ ) {Threads [I]. Start (); console. Readline ();}}}} 

 

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.