Could you describe two methods of synchronizing multi-threaded write access performed
on a class member?
Please could any one help me what is this meant to do and what is the right answer.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When you change data in C#, something that looks like a single operation may be compiled into several instructions. Take the following class:
When you build it, you get the following IL code:
Now, say you have a
Numberobject and two threads call itsAddmethod like this:If you want the result to be 5 (0 + 2 + 3), there’s a problem. You don’t know when these threads will execute their instructions. Both threads could execute
IL_0003(pushing zero onto the stack) before either executesIL_000a(actually changing the member variable) and you get this:The last thread to finish ‘wins’ and at the end of the process,
ais 2 or 3 instead of 5.So you have to make sure that one complete set of instructions finishes before the other set. To do that, you can:
1) Lock access to the class member while it’s being written, using one of the many .NET synchronization primitives (like
lock,Mutex,ReaderWriterLockSlim, etc.) so that only one thread can work on it at a time.2) Push write operations into a queue and process that queue with a single thread. As Thorarin points out, you still have to synchronize access to the queue if it isn’t thread-safe, but it’s worth it for complex write operations.
There are other techniques. Some (like
Interlocked) are limited to particular data types, and there are even more (like the ones discussed in Non-blocking synchronization and Part 4 of Joseph Albahari’s Threading in C#), though they are more complex: approach them with caution.