Hi, I've just started playing around with C# multithreading and I've encountered some strange behaviour. I have two procedures, each of which does some integer arithmentic and takes about 3 seconds to execute on a P4:
private volatile int intResult1 = 0;
public void WorkerThreadProc1()
{
for (int i = 0; i < 10000; i++)
for (int j = 0; j < 100000; j++)
intResult1 += i * j;
}private volatile int intResult2 = 0;
public void WorkerThreadProc2()
{
for (int i = 0; i < 10000; i++)
for (int j = 0; j < 100000; j++)
intResult2 += i * j;
}
And I'm creating a seperate execution thread for each:
Thread thread1 = new Thread(new ThreadStart(WorkerThreadProc1));
Thread thread2 = new Thread(new ThreadStart(WorkerThreadProc2));
Now if I execute these threads sequentiallly then it takes 6 seconds to run, as expected:
thread1.Start();
thread1.Join();
thread2.Start();
thread2.Join();
However, if I switch two of those lines to try to get them to execute concurrently then it takes a whopping 34 seconds:
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
The point of all this is to try to get the routines to execute concurrently if the user has a core2 duo or whatever, what am I doing wrong? I understand there'll be some overhead from multithreading on a single core CPU, but 90% of CPU time is ridiculous.
Mark

AlanRank #669 · 3.6K reputationPosted Sep 27, 2007, 10:42 AM EDT
I've just run the exact same code a number of times on my old (and relatively slow) single core Pentium M laptop and the threads always ran in between 10 and 11 seconds with no discernible difference between them.
So, I don't know what to make of your results, Mark, which seem anomalous :-/
Did you have any other applications running at the time? I closed everything else down and ran the tests from the command line to minimize any distortion caused by thead switching between processes.
Mark Feldman11 reputationPosted Sep 27, 2007, 9:18 PM EDT
Got it figured out, with a bit of help from the MSDN forum. Both result variables are in the same cache line. The += command causes both threads to both read from and write to the cache line, there's a depedancy there that some machines apparently can't deal with. Changing to operation to an assignment, or boxing the result variables to ensure they're in different cache lines, fixes the problem.