我正嘗試使用線程來獲取素數列表。但是,當我運行該程序時,我在結果中得到冗餘素數。獲取意想不到的多線程行爲
static void Main(string[] args)
{
try
{
var r2 = DoThread();
Array.Sort(r2);
}
catch (Exception e)
{ }
}
public static int[] DoThread()
{
var task = new List<MyThread>(){
new MyThread(){start = 3, end = 25000},
new MyThread(){start = 25001, end = 50000},
new MyThread(){start = 50001, end = 75000},
new MyThread(){start = 75001, end = 100000-3}
};
var threads = new List<Thread>()
{
new Thread(task[0].MyDelegate),
new Thread(task[1].MyDelegate),
new Thread(task[2].MyDelegate),
new Thread(task[3].MyDelegate)
};
threads.ForEach(t => { t.Start(); });
threads.ForEach(t => { t.Join(); });
var res = new List<int>();
task.ForEach(t => res.AddRange(t.result));
return res.ToArray();
}
public class MyThread
{
public int[] result;
public int start;
public int end;
public void MyDelegate()
{
IEnumerable<int> numbers = Enumerable.Range(start, end);
var parallelQuery =
from n in numbers
where Enumerable.Range(2, (int)Math.Sqrt(n)).All(i => n % i > 0)
select n;
result = parallelQuery.ToArray();
}
}
「冗餘素數」是什麼意思? –
你是指DUPLICATE素數? – Polyfun
我得到相同的素數,比如說11,在合併所有四個後的最終結果數組中得到兩次。,,, 11,11,13,17,19,19,23 ... –