锁定并将参数传递给多线程代码

时间:2018-02-15 21:19:14

标签: c# multithreading locking

我想使用如下的多线程程序,但是当我运行程序时,R1,R2和R3不一样。

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ParallelFor
{
   class Program
   {
       static void Main()
       {
           Console.WriteLine("Program started");
           double R1 = 0.0;
           double R2 = 0.0;
           double R3 = 0.0;
           var t1 = new Thread(() => TestCounter(1000, ref R1, 1));
           var t2 = new Thread(() => TestCounter(1000, ref R2, 2));
           var t3 = new Thread(() => TestCounter(1000, ref R3, 3));
           t1.Start();
           t2.Start();
           t3.Start();

           do
           {
               Thread.Sleep(1000);
               Console.WriteLine("waiting...");
           } while (t1.IsAlive == true && t2.IsAlive == true &&   t3.IsAlive == true);

           Console.WriteLine("inside R1: {0}", R1);
           Console.WriteLine("inside R2: {0}", R2);
           Console.WriteLine("inside R3: {0}", R3);
           Console.WriteLine("Program finished");
           Console.ReadLine();
       }
       static void TestCounter(int counter, ref double result, int No)
       {
               for (int i = 0; i < counter + 1; i++)
                  for (int j = 0; j < counter; j++)
                      for (int k = 0; k < counter; k++)
                          result += (double)i;
       }
   }
} 

1 个答案:

答案 0 :(得分:2)

第一个线程就绪后,do循环结束。

我想你想要

while ( t1.IsAlive || t2.IsAlive || t3.IsAlive );

将使do循环保持循环,直到所有测试都准备就绪。