Is it possible to update shared memory in some thread while its value is still not visible to the main thread?

I read this article about volatile fields in C #.

using System;
using System.Threading;
class Test
{
   public static int result;   
   public static volatile bool finished;
   static void Thread2() {
      result = 143;    
      finished = true; 
   }
   static void Main() {
      finished = false;
      // Run Thread2() in a new thread
      new Thread(new ThreadStart(Thread2)).Start();
      // Wait for Thread2 to signal that it has a result by setting
      // finished to true.
      for (;;) {
         if (finished) {
            Console.WriteLine("result = {0}", result);
            return;
         }
      }
   }
}

As you can see, there is a loop in the main thread waiting to set the volatile flag to print the “result”, which is assigned 143 before the flag is set. The explanation says that if the flag was not declared as volatie, then

it is permissible for the store to be visible to the main stream after the store shuts down

Did I miss something? Even if it wasn’t volatile, how did it happen that the program would ever be printed 0.

+3
source share
1 answer

Volatile ( ) , , (, - ) , , 0 - . , , .

, concurrency, , , . . , .NET.

+3

All Articles