multithreading - Interview Question on .NET Threading -


Can you describe two methods of synchronizing multi-threaded write access on a class member?

Please anybody can help me what that means and what is the correct answer.

When you change the data in C #, some instructions like some of the same operations seem to have many instructions You can compile in the following categories:

  Public category number {Private int A = 0; Add Public Zero (int b) {a + = b; }}  

When you create it, you get the following IL code:

  IL_0000: nop IL_0001: ldarg.0 IL_0002: dup // Value of private variable 'a' on stack IL_0003: ldfld int32 Simple.Number :: a // Push the value of argument 'b' on stack IL_0008: ldarg.1 // Adds the top two values ​​of the stack together il / 20009: Add / / Set the value to 'A' at the top of the stack IL_000a: stfld int32 Simple.Number :: One IL_000f: ret  

Now, say you have a number object and two threads its add method is called this way :

  Nanbrkaed (2); // thread 1 number.Add (3); // Thread 2  

If you want result 5 (0 + 2 + 3), then there is a problem. You do not know that these threads will execute their instructions. Before executing IL_000a (actually changing member variable), both threads can execute IL_0003 (pushing zero on stack) and you can get it :

  A = 0 + 2; // thread 1a = 0 + 3; // Thread 2  

The final thread to finish 'win' and at the end of the process, instead of one 5 is 2 or 3.

You must make sure that a complete set of instructions will end before the second set. To do this, you can:

1) Stop accessing a class member using one of the many members (e.g.,, etc.) so that only a thread A time could work on

2) Press the process of writing in a queue and do the queue process with the same thread. As Thorarin explains, you still need to synchronize access to the queue if this thread is not secure, but it is worth it for complex writing tasks.

Other techniques. Some types (such as) are limited to specific data types, and even more (as discussed and as), although they are more complex: contact them with caution.


Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -