none
How thread safety is achieved with Sync blocks, in .Net CLR? RRS feed

  • Question

  • After a reading, I could understand C#'s Lock internally Uses Monitor.Enter and the Monitor.Enter acquires a lock for a critical section by using .Net CLR's Sync block flags.

    However, I am interested to understand the logic/tech in acquiring lock when 2 parallel threads are executing to acquire the sync block flag at a same exact time. Considering Acquiring lock is also an operation on top of the user code, How is it possible that the same operation from different threads on a shared resource at a same time can't conflict.

    Thursday, June 20, 2019 5:06 AM

All replies

  • Hi MuthukumarPL,

    Thank you for posting here.

    For your question, when the code is executed by a thread, an attempt is made to acquire the lock. If the lock has already been acquired by another thread, the thread blocks until the lock becomes available. When the thread exits the synchronized block of code, the lock is released, no matter how the thread exits the block.

    For more details, please refer to the MSDN document.

    https://docs.microsoft.com/en-us/dotnet/standard/threading/synchronizing-data-for-multithreading

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, June 21, 2019 9:21 AM
    Moderator
  • This is pretty well documented.

    According to Microsoft: The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

    The logic is that the lock keyword calls Enter at the start of the block and Exit at the end of the block. The lock keyword actually handles Monitor class at back end.

    Keep in mind, that using locks can have a negative impact on performance in a multi-threaded environment. If you need to use lock, make sure the code within the lock block can process very quickly.

    I recommend you take a look at the following article as well. Goes over best practices.

    https://www.pluralsight.com/guides/lock-statement-best-practices


    william xifaras


    Monday, June 24, 2019 3:09 PM