Simply put, threading is parallel code execution. If you have a computer with multiple processors, chances are you have seen the effects of multithreaded programs. For this code example, there's two calculations done multiple times on different threads. First one is for Kenetic Energy, Ke = (1/2) * M * V^2 (Kenetic Energy = half mass times velocity squared) and Ohms Law of V = IR (voltage = impedence * resistance). In this example, notice the Kenetic Energy calculation completes before the Ohms Law.
More detail explinations and examples can be found here http://www.albahari.com/threading/.
const long howManyTimes = 500000000;
static void Main(string[] args)
{
Console.WriteLine("Enter Mass : ");
double mass = 0;
double.TryParse(Console.ReadLine(), out mass);
Console.WriteLine("Enter Velocity : ");
double velocity = 0;
double.TryParse(Console.ReadLine(), out velocity);
//spawn a thread. This does NOT start the execution of that thread.
Thread thread = new Thread(delegate() { CalculateKeneticEnergy(mass, velocity); });
Console.WriteLine("Enter Voltage : ");
double v = 0;
double.TryParse(Console.ReadLine(), out v);
Console.WriteLine("Enter Ohms :");
double resistance = 0;
double.TryParse(Console.ReadLine(), out resistance);
int z = 0;
double i = 0;
//start the othe calculation
thread.Start();
//Calcuate Amps
while (z < howManyTimes)
{
i = v / resistance;
z++;
}
Console.WriteLine("Amps = " +i.ToString());
//Join tells the host process to wait on other spawned threads, such as this one.
thread.Join();
Console.ReadLine();
}
static void CalculateKeneticEnergy(double mass, double velocity)
{
int i = 0;
double kE = 0;
while (i < howManyTimes)
{
kE = (0.5 * mass * (velocity * velocity)) / 2;
i++;
}
Console.WriteLine("Kenetic Energy = " + kE.ToString());
}