Reputation: 2819
I'm given a problem to demonstrate a benchmark for executing functions using Single and Multithread. Am I doing right here? If yes, how can I do so without using Join(). If no, suggest me.
Code
class Threading1
{
static void Main (string[] args)
{
Stopwatch timerMain, timerThreads;
// Main thread
timerMain = Stopwatch.StartNew ();
func1();
func2();
func3();
timerMain.Stop ();
Console.WriteLine ("Time taken for Main thread: " + timerMain.ElapsedMilliseconds);
// Other threads
Thread t1 = new Thread (() => Threading1.func1 ());
Thread t2 = new Thread (() => Threading1.func2 ());
Thread t3 = new Thread (() => Threading1.func3 ());
timerThreads = Stopwatch.StartNew ();
t1.Start(); t1.Join();
t2.Start(); t2.Join();
t3.Start(); t3.Join();
timerThreads.Stop ();
Console.WriteLine ("Time taken for Other threads: " + timerThreads.ElapsedMilliseconds);
}
// Find maximum value in an array
static void func1()
{
// Code here.
}
// Find minimum value in an array
static void func2()
{
// Code here.
}
// Find average value of an array
static void func3()
{
// Code here.
}
}
Output
Time taken for Main thread: 44
Time taken for other threads: 10
Upvotes: 3
Views: 379
Reputation: 24913
I advice you to use Tasks and method WaitAll to wait, when all tasks are completed.
timerThreads = Stopwatch.StartNew();
var t1 = Task.Run(() => Threading1.func1());
var t2 = Task.Run(() => Threading1.func2());
var t3 = Task.Run(() => Threading1.func3());
Task.WaitAll(t1, t2, t3);
timerThreads.Stop ();
Console.WriteLine ("Time taken for Other threads: " + timerThreads.ElapsedMilliseconds);
In your solution there is no parallel working, all threads are execition one by one.
Upvotes: 2