Listing 6: Three threads concurrently incrementing a shared variable 10,000,000 times

#using <mscorlib.dll>
using namespace System;
using namespace System::Threading;

bool interlocked = false;
const int maxCount = 10000000;
/*1*/   __int64 value = 0;

__gc class Th08
{

public:
   void TMain()
   {
      if (interlocked)
      {
         for (int i = 1; i <= maxCount; ++i)
         {
/*2*/            Interlocked::Increment(&value);
         }
      }
      else
      {
         for (int i = 1; i <= maxCount; ++i)
         {
/*3*/            ++value;
         }
      }
   }

};

int main(int argc, char *argv[])
{
   if (argc == 2)
   {
      if (argv[1][0] == 'Y' || argv[1][0] == 'y')
      {
         interlocked = true;
      }
   }

   Thread *t1 = new Thread(new ThreadStart(new Th08(),
      &Th08::TMain));
   Thread *t2 = new Thread(new ThreadStart(new Th08(),
      &Th08::TMain));
   Thread *t3 = new Thread(new ThreadStart(new Th08(),
      &Th08::TMain));

   t1->Start();
   t2->Start();
   t3->Start();
   t1->Join();
   t2->Join();
   t3->Join();

   Console::WriteLine(S"After {0} operations, value = {1}",
      (3 * maxCount).ToString(), value.ToString());
}
— End of Listing —