我在我的Windows窗体C#应用这些代码:并行功能,在C#中返回不同的结果
private void button7_Click(object sender, EventArgs e)
{
ThreadStart starter = delegate { thread_func(2, 1000000); };
thread1_thread = new Thread(starter);
starter = delegate { thread_func(1000000, 2000000); };
thread2_thread = new Thread(starter);
starter = delegate { thread_func(2000000, 3000000); };
thread3_thread = new Thread(starter);
starter = delegate { thread_func(3000000, 4000000); };
thread4_thread = new Thread(starter);
thread1_thread.Start();
thread2_thread.Start();
thread3_thread.Start();
thread4_thread.Start();
}
void thread_func(decimal input1,decimal input2)
{
for (; input1 < input2; input1++)
{
threadNumbers_list.Add(input1);
if (input1 % 2 != 0)
{
if (isPrime_func(input1))
{
PrimeNumbers_decimal_list.Add(input1);
}
}
}
}
public static Boolean isPrime_func(decimal number)
{
decimal boundary = (decimal)Math.Floor(Math.Sqrt((double)number));
if (number == 1) return false;
if (number == 2) return true;
for (decimal i = 2; i <= boundary; ++i)
{
if (number % i == 0) return false;
}
return true;
}
我每次运行单击该按钮,我得到不同的结果。我尝试了很多东西,但无法弄清楚为什么会发生这种情况。即使是在较低的范围内发生。例如,在100个数字的范围内,它总是给出相同的结果。 有些时候,我的清单计数达到283138,有时候是283131和其他接近的数字。
另一个奇怪的是,当我评论检查偶数时,操作比此模式花费的时间更短。怎么了?
'threadNumbers_list'和'PrimeNumbers_decimal_list'可能不是线程安全的。 –
我创建该列表只是为了检查是否所有迭代都发生! – ACE
'PrimeNumbers_decimal_list'呢?另外,你如何等待线程完成?你使用'Thread.Join'吗? –