Multithreaded issue updating value

Itโ€™s hard for me to understand why multithreading does not update the values โ€‹โ€‹until the stream ends. Does a separate thread have its own copy of links or values?

If not, as far as I know, the code below should work correctly when calling MyMethod, but often it does not instantiate some MyType objects in the array before thread.IsAlive becomes false:

 class MyClass { static MyType[] obj = new MyType[Environment.ProcessorCount - 1]; void MyMethod() { Thread[] threads = new Thread[Environment.ProcessorCount - 1]; for (int i = 0; i < Environment.ProcessorCount - 1; i++) { threads[i] = new Thread(() => FillObjects(i)); threads[i].Priority = ThreadPriority.AboveNormal; threads[i].Start(); } while (threads[i].Any(c => c.IsAlive)) { Thread.Sleep(50); } } void FillObjects(int i) { obj[i] = new MyType(); //perform actions with obj[i] to fill it with necessary values } } 
+5
source share
2 answers

You need to assign the value of the loop variable to a local variable. Otherwise, it is possible that the first execution of FillObjects(i) is executed after i been incremented, so FillObjects(0) never called, and therefore obj[0] never assigned.

 void MyMethod() { Thread[] threads = new Thread[Environment.ProcessorCount - 1]; for (int i = 0; i < Environment.ProcessorCount - 1; i++) { int local = i; threads[i] = new Thread(() => FillObjects(local)); threads[i].Priority = ThreadPriority.AboveNormal; threads[i].Start(); } while (threads.Any(c => c.IsAlive)) { Thread.Sleep(50); } } 
+6
source

On a multiprocessor machine (which you should have), the results written to a memory location in one thread may not be displayed in another thread due to caching. Use Thread.VolatileRead and Thread.VolatileWrite to read and write through the cache.

Cf. chapter for streaming in C # 3.0 in a nutshell for an explanation. (Look for the question โ€œIs it possible for the Wait method to writeโ€œ False โ€?". This example is basically your case.)

-1
source

All Articles