Multithreaded secret in C ++ with Boost

static void testlock() { for(int i=0;i<10000000;i++) { float f=2.0/i; } } static void TEST() { cout<<"Start testing" <<endl; unsigned int startClock; for(int i=1;i<=10;i++) { startClock = clock(); vector<boost::thread*> threads; for(int j=0;j<i;j++) threads.push_back(new boost::thread(&testlock)); for(int j=0;j<i;j++) { threads[j]->join(); delete threads[j]; } cout << i << " threads: "<< clock()-startClock << endl; } } 

Conclusion:

 Start testing 1 threads: 180000 2 threads: 350000 3 threads: 540000 4 threads: 730000 5 threads: 900000 6 threads: 1080000 7 threads: 1260000 8 threads: 1510000 9 threads: 1660000 10 threads: 1810000 

I run this code on a quad-core PC (Core2Quad, 4 cores without a hyper-thread), so I expected that 1-4 threads would take about the same time. Instead, it seems that only one core is used. What am I missing here?

thanks

Update:

-I use Eclipse CDT under Ubuntu Linux

- I tried the same with Pthread and get the same result

+4
source share
2 answers

My colleague found a solution: clock () measures the processor cycles, so if two threads work, it works twice as fast. Deadlines with gettimeofday gave the expected result.

+3
source

First of all, at i=0 2.0/i is divided by zero (sorry, as Igor correctly noted in the comments, it is valid with floating point arithmetic and, in this case, leads to + infinity.

At the same time, even if you fix this, your testlock function is likely to be optimized to nothing, because the result is never used.

So, at the moment you are just measuring the overhead of creating and combining threads, so a linear increase.

+1
source

All Articles