InterviewSolution
| 1. |
What are Interlocked functions? |
|
Answer» Shared variables in C# are not thread-safe. It means that any operation on a variable can be corrupted due to multiple threads. To prevent these dirty reads, C# allows the use of interlocked functions to change the value of shared variables in multithreading code. Interlocked functions only support int, long, double and float data types, as shown by some of the examples below: 1) Add(ref int address1, int value): Interlocked function to add a value into an int variable safely. 2) Increment(ref int address1): Interlocked function to increment value of an int variable safely by 1. 3) Decrement(ref int address1): Interlocked function to decrement value of an int variable safely by 1. 4) Exchange(ref int address1, int value): Interlocked function to replace the value of an int variable safely. 5) CompareExchange(ref int address1, int newValue, int toBeValue): Interlocked function to replace the value of an int variable safely only if the existing value is equal to passed toBeValue. |
|