Protecting shared resources in C sharp Arabic #91

 


Protecting shared resources in C sharp Arabic #91

Suggested Videos

❑ What happens if shared resources are not protected from concurrent access in multithreaded program.

❑ How to protect shared resources from concurrent access.

What happens if shared resources are not protected from concurrent access in multithreaded program ? The output or behavior of the program can become inconsistent if the shared resources are not protected from concurrent access in multithread program

This program is single-threaded program. In the Main () method , AddOneMillion() method is called 3 times, and it updates the Total filed



Every time we run the above program, we get a different output . The inconsistent output is because the Total filed which is a shared resource is not protected from concurrent access by multiple threads .the operator ++ is not thread safe.



Using Interlocked.Increment() : Increments a specified variable and stores the result, as an atomic operation.



Which option s better? From a performance perspective using interlocked class is better over using locking . Locking locks out all the other threads except a single thread to read and increment the Total variable . This will ensure that the Total variable is updated safely . The downside is that since all the other threads are looked out , there is a performance hit.

The Interlocked class can be used with addition/ subtraction (increment ,decrement . add, etc..) on and int or long field. The Interlocked class has methods for incrementing. Decrementing . Adding and reading variables atomically.



The following code prints the time taken in ticks. 1millisecond consists of 10000 ticks


Please Note: You can use the TimeSapn object to find ticks per second , ticks per millisecond etc.


Follow Us

YouTube

 If you want to download pptx : click Telegram

Facebook

Twitter

Instagram

Tik Tok









إرسال تعليق

أحدث أقدم