I implement sum element of array using multi threading but my question is when my program work with one thread the time is better than using 6 thread . I am using a CPU with 8 threads.What am I wrong
public static int threadss = 7;
public const int count = 1000000;
public static List<int> a = new List<int>();
public static int numberofthreads;
public static long[] sum=new long[threadss];
public static long total_sum=0;
public static long part = 0;
static void Main(string[] args)
{
Random r = new Random();
for (int i = 1; i <= count; i++)
{
a.Add(i);
}
numberofthreads = threadss;
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
Thread[] threadsarray = new Thread[numberofthreads];
List<Thread> threads = new List<Thread>();
for (int i = 0; i < numberofthreads; i++)
{
threadsarray[i] = new Thread(new ParameterizedThreadStart(myThreadMethod));
threadsarray[i].Start(i);
}
for (int i = 0; i < numberofthreads; i++)
{
threadsarray[i].Join();
}
for(int i= 0; i < numberofthreads; i++)
{
total_sum += sum[i];
}
watch.Stop();
Console.WriteLine("Time is " + watch.ElapsedMilliseconds.ToString());
Console.WriteLine("sum is "+ total_sum);
}
static void myThreadMethod(object threadid)
{
int thid = (int)threadid;
for (int i = (thid * (a.Count / numberofthreads));i < (thid + 1) * a.Count / numberofthreads; i++)
{
sum[thid] += a[i];
}
}
sum
, to do that. This is an operation you’d normally want to vectorize. \$\endgroup\$