main() function
class Multithreading
{
public void DataFillFull(int[] arr, ConcurrentBag cBag)
{
int fullen = arr.Length;
for (int i = 0; i < fullen; i++)
{
cBag.Add(arr[i]);
}
}
public void DataFill(int[] arr, ConcurrentBag cBag, bool ascending)
{
int fullen = arr.Length;
int halfLen = fullen / 2;
if (ascending)
{
for (int i = 0; i < halfLen; i++)
{
cBag.Add(arr[i]);
}
}
else
{
for (int i = fullen; i > halfLen; i--)
{
cBag.Add(arr[i - 1]);
}
}
}
public void Main(string[] args)
{
/* Measure */
string input;
long mSeconds = 0;
float average = 0;
int repeats = 0;
Stopwatch stopwatch = new Stopwatch();
begin:
int[] ints = new int[9000000];
for (int i = 0; i < 9000000; i++)
{
ints[i] = i;
}
ConcurrentBag cBag = new ConcurrentBag();
stopwatch.Start();
// Multithreading
Task t1 = Task.Factory.StartNew(() => DataFill(ints, cBag, true));
Task t2 = Task.Factory.StartNew(() => DataFill(ints, cBag, false));
Task.WaitAll(t1, t2);
// Singlethreading
//DataFillFull(ints, cBag);
stopwatch.Stop();
Console.WriteLine("Repeat? y/anykey");
input = Console.ReadLine();
if (input == "y")
{
repeats++;
mSeconds += stopwatch.ElapsedMilliseconds;
average = mSeconds / repeats;
Console.WriteLine(stopwatch.ElapsedMilliseconds);
Console.WriteLine($"For {repeats} repeats, average time is {average} miliseconds.");
stopwatch.Reset();
goto begin;
}
else
{
Console.WriteLine();
repeats++;
mSeconds += stopwatch.ElapsedMilliseconds;
average = mSeconds / repeats;
Console.WriteLine(stopwatch.ElapsedMilliseconds);
Console.WriteLine($"For {repeats} repeats, average time is {average} miliseconds.");
Console.ReadKey();
Environment.Exit(0);
}
}
}