I had a bit of struggle to write a title to this... it seems like such a weird problem that should not occur!
This is my problem: I'm trying to make a program that uses 16 threads to calculate all the prime numbers between 0 and 16000000 as fast as possible, giving each thread a range of (0-16)=x*1000000 to (x+1)*1000000 to calculate all the primes using my function, prime(). So every thread does it's own million. Every time it finds a prime number it adds it to the array primes[].
Thread[] threads = new Thread[16];
ulong[] primes = new ulong[17000000];
ulong start, stop;
Thread t = new Thread(() => Console.ReadKey());
for (int i = 0; i < 16;)
{
start = Convert.ToUInt64(i * 1000000);
stop = Convert.ToUInt64((i + 1) * 1000000);
threads[i] = new Thread(() =>
{
ulong start2 = start;
ulong stop2 = stop;
Thread.Sleep(5000);
for (ulong j = start2; j <= stop2; j++)
{
if (prime(j) == true)
{
primes[j] = j;
total += 1;
}
}
Console.WriteLine("another thread done calculating");
});
threads[i].Start();
i++;
And then writing them into a file, however the problem is in the code above! it usually starts at 4000000, 3000000 or 2000000, when its supposed to start at 0, then work its way up to those higher numbers!
This is the whole program:
using System;
using System.Threading;
using System.IO;
namespace threading
{
class Program
{
static bool prime(ulong primtal)
{
bool IsPrime = false;
for (ulong i = 2; i <= (Convert.ToUInt64(Math.Sqrt(primtal))); i++)
{
if (primtal == 2 || primtal == 3)
{
IsPrime = true;
break;
}
else if (primtal % i == 0)
{
IsPrime = false;
break;
}
else
{
IsPrime = true;
}
}
return IsPrime;
}
static int total = 0, counter = 0;
static void Main(string[] args)
{
Thread[] threads = new Thread[16];
var timer = new Timer(TimerMethod, null, 0, 5000);
ulong[] primes = new ulong[17000000];
ulong start, stop;
Thread t = new Thread(() => Console.ReadKey());
for (int i = 0; i < 16;)
{
start = Convert.ToUInt64(i * 1000000);
stop = Convert.ToUInt64((i + 1) * 1000000);
threads[i] = new Thread(() =>
{
ulong start2 = start;
ulong stop2 = stop;
Thread.Sleep(5000);
for (ulong j = start2; j <= stop2; j++)
{
if (prime(j) == true)
{
primes[j] = j;
total += 1;
}
}
Console.WriteLine("another thread done calculating");
});
threads[i].Start();
i++;
}
Console.ReadKey();
StreamWriter SW = new StreamWriter("PATH");
for (int f = 1; f < primes.Length; f++)
{
if (primes[f] != 0)
{
SW.Write(f + " ");
counter += 1;
}
if (counter == 10)
{
SW.Write("\n");
counter = 0;
}
}
SW.Close();
Console.WriteLine("Done! it should all be written into: \"PATH\"");
}
private static void TimerMethod(object o)
{
Console.WriteLine(total);
}
}
}
I'm on a windows 10 machine and I'm using the 3.1 dotnet framwork
How do I make it so thread 0 starts at 0 and then thread 1 starts at 1000000 and so on, like its supposed to?