【发布时间】:2016-02-17 18:54:27
【问题描述】:
我的 Windows 窗体 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可能不是线程安全的。 -
我创建该列表只是为了检查是否所有迭代都发生了!
-
PrimeNumbers_decimal_list怎么样?另外,您如何等待线程完成?你用Thread.Join吗? -
我检查 VS 事件并等待所有线程退出并检查应用程序 cpu 使用情况,然后单击另一个显示 primenumberlist 计数的按钮
-
我创建了多线程多素数函数但无法解决!
标签: c# multithreading primes