Describe the usage analysis of the lock keyword in C multithreading

  • 2020-05-12 03:08:31
  • OfStack

This article introduces the C# lock keyword. C# provides one keyword, lock, which defines a piece of code as a mutex (critical section). The mutex allows only one thread to enter execution at a time, while other threads must wait.
Each thread has its own resources, but the code area is Shared, meaning that each thread can perform the same function. The problem that this can cause is that several threads execute a function at the same time, resulting in chaotic data and unpredictable results, so we must avoid this situation.
C# provides a keyword, lock, that defines a piece of code as a mutex (critical section), which allows only one thread to enter execution at a time, while other threads must wait. The C# lock keyword is defined as follows:
lock (expression) statement_block
expression represents the object you want to trace, usually an object reference.
If you want to protect an instance of a class, like 1, you can use this; If you want to protect a static variable (such as a mutex inside a static method), use the class name.
statement_block is the code for the mutex, which can only be executed by one thread at a time.
Here is a typical example of using the C# lock keyword, with the comments illustrating the use and use of the C# lock keyword.
Here's an example:

using System; 
using System.Threading; 
namespace ThreadSimple
{ 
    internal class Account
    { 
        int balance; // The balance of 
        Random r=new Random(); 
        internal Account(int initial)  
        {  
            balance=initial; 
        }
        internal int Withdraw(int amount) // Take back 
        { 
            if(balance<0) 
            {  
                // if balance Less than 0 Throw an exception   
                throw new Exception("NegativeBalance");// A negative   The balance of  
            } 
            // The following code is guaranteed to change in the current thread balance Before the value is completed  
            // No other thread will execute this code to modify it balance The value of the   
            // As a result, balance The value of theta cannot be less than theta 0 the   
            lock(this)  
            { 
                Console.WriteLine("CurrentThread:"+Thread.CurrentThread.Name); 
                // If there is no lock Keyword protection, then, may be performed at the end if Conditional judgment ( Set up ) after   
                // In addition 1 Four threads execute balance=balance-amount To modify the balance The value of the  
                // This change is not visible to this thread, so it may cause this if The condition is no longer valid  
                // However, the thread continues to execute  balance=balance-amount , so as a result balance May be smaller than the 0 
                if(balance>=amount) 
                { 
                    Thread.Sleep(5);
                    balance=balance-amount; 
                    return  amount; 
                }  else 
                { 
                    return 0;
                    //transactionrejected 
                } 
            }  
        }
        internal void DoTransactions()// A withdrawal transaction 
        {
            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();
            }
        }
    } 
} 


Related articles: