C # Lock and monitor introduction (multi-thread Concurrency Control)

Source: Internet
Author: User
    Here we will introduce the C # Lock keyword. It can define a piece of code as a critical section. A mutex can only be executed by one thread at a time, while other threads must wait.

     

    C # language is worth learning a lot. Here we mainly introduce the C # Lock keyword, including the locking of an object in the monitor class.

    C # provides a lock keyword, 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. In C #, 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, you can generally use this;
    ◆ If you want to protect a static variable (for example, the mutex code segment is inside a static method), 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:

 
 
  1. Using system;
  2. Using system. Threading;
  3. Namespace threadsimple
  4. {
  5. Internal class account
  6. {
  7. Int balance;
  8. Random r = new random ();
  9. Internal account (INT initial)
  10. {
  11. Balance = initial;
  12. }
  13. Internal int withdraw (INT amount)
  14. {
  15. If (balance< 0)
  16. {
  17. // If the balance is smaller than 0, an exception is thrown.
  18. Throw new exception ("negative balance ");
  19. }
  20. // The following Code ensures that the balance value is modified by the current thread.
  21. // No other threads will execute this code to modify the balance value.
  22. // Therefore, the balance value cannot be smaller than 0.
  23. Lock (this)
  24. {
  25. Console. writeline ("current thread:" + thread. currentthread. Name );
  26. // If the lock keyword is not protected, it may be after the if condition is determined.
  27. // Another thread executes balancebalance = balance-amount and modifies the balance value.
  28. // This modification is invisible to this thread, so it may cause the if condition to be invalid.
  29. // However, this thread continues to execute balancebalance = balance-amount, so the balance may be less than 0
  30. If (balance>= Amount)
  31. {
  32. Thread. Sleep (5 );
  33. Balancebalance = balance-amount;
  34. Return amount;
  35. }
  36. Else
  37. {
  38. Return 0; // Transaction rejected
  39. }
  40. }
  41. }
  42. Internal void dotransactions ()
  43. {
  44. For (INT I = 0; I< 100; I ++)
  45. Withdraw (R. Next (-50,100 ));
  46. }
  47. }
  48. Internal class test
  49. {
  50. Static internal thread [] threads = new thread [10];
  51. Public static void main ()
  52. {
  53. Account ACC = new account (0 );
  54. For (INT I = 0; I< 10; I ++)
  55. {
  56. Thread t = new thread (New threadstart (Acc. dotransactions ));
  57. Threads [I] = T;
  58. }
  59. For (INT I = 0; I< 10; I ++)
  60. Threads [I]. Name = I. tostring ();
  61. For (INT I = 0; I< 10; I ++)
  62. Threads [I]. Start ();
  63. Console. Readline ();
  64. }
  65. }
  66. }

The monitor class locks an object.

When multiple threads share an object, a problem similar to that of public code may also occur. In this case, the C # Lock keyword should not be used. System is used here. A kind of Monitor In threading is called a monitor, which provides a solution to share resources with threads.

The monitor class can lock an object. A thread can operate on this object only when this lock is obtained. The object lock mechanism ensures that only one thread can access this object at a time point that may cause confusion. Monitor must be associated with a specific object, but because it is a static class, it cannot be used to define the object, and all its methods are static, objects cannot be referenced. The following code uses monitor to lock an object:

 
 
  1. ......
  2. Queue oqueue = new Queue ();
  3. ......
  4. Monitor. Enter (oqueue );
  5. ... // Now the oqueue object can only be manipulated by the current thread
  6. Monitor. Exit (oqueue); // release the lock

As shown above, when a thread calls monitor. when the enter () method locks an object, this object will be owned by it. Other threads want to access this object, only waiting for it to use monitor. the exit () method releases the lock. To ensure that the thread can release the lock in the end, you can write the monitor. Exit () method into the finally code block in the try-catch-Finally structure.

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.