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;}
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