I have a simple class designed to play around with threading. It has a member variable, num, which is initialized to 0, and a method called modify which increments and then decrements num a high number of times. When the program runs, it creates two threads which both run modify, and then starts a timer and starts the threads. It uses a while loop to wait for both threads to finish executing, and then stops the timer and prints the time elapsed to the console. The class:
public class Threading
{
public static void Main()
{
Threading t = new Threading();
t.demo();
}
private int num = 0;
public void doThreading()
{
Thread t1 = new Thread(modify);
Thread t2 = new Thread(modify);
t1.Start();
t2.Start();
Stopwatch timer = new Stopwatch();
timer.Start();
while (thread1.IsAlive || thread2.IsAlive)
{
}
timer.Stop();
Console.WriteLine("Took: " + timer.ElapsedMilliseconds + " milliseconds");
Console.Read();
}
public void modify()
{
for (int i = 0; i < 1000000000; i++)
{
count++;
count--;
}
}
}
After running the program, num will not be 0 because of race conditions. When I add locks to the modify method so that num is 0 after running the program:
public void modify()
{
for (int i = 0; i < 1000000000; i++)
{
lock (this) { count++; }
lock (this) { count--; }
}
}
Then the program takes 8 times as long to execute. I cannot figure out why it would be taking so much longer, I would expect, at most, for it to take 4 times as long to execute. Any idea why it is taking so much longer?