Greetings.

I'm very new to QtConcurrent, and I have very little experience in threading in general. I went over some examples today in the Qt docs, and I can't figure out why my multi-threaded code runs slower than the single-threaded version.

This code is basically a modified version of what I found in the docs.

Qt Code:
  1. #include <QThread>
  2. #include <QApplication>
  3. #include <qtconcurrentmap.h>
  4. #include <iostream>
  5. #include <QtConcurrentRun>
  6. using namespace std;
  7.  
  8. int Func(const int &n){
  9.  
  10. //Some random calculations...
  11. int a = rand() % 3, b = rand() % 4, c = rand() % 5;
  12. int x = a * a, y = b * b, z = c * c;
  13. int u = a + x, v = b + y, w = c + z;
  14. int d = u - v * w;
  15. if( d > 0 ){
  16. d = a / x / u;
  17. }else{
  18. d = b / y / v;
  19. }
  20. for(int i = 1; i < 10; ++i){
  21. for(int j = 1; j < 30; ++j){
  22. d = rand() % 5 + 3;
  23. d /= 2;
  24. d *= rand() % 4;
  25. }
  26. }
  27. return d * n;
  28. }
  29.  
  30. int main(int argc, char *argv[]){
  31.  
  32. QApplication app(argc, argv);
  33. const int SIZE = 500000;
  34. QVector<int> data;
  35.  
  36. for(int i = 0; i < SIZE; ++i){
  37. data.push_back(i);
  38. }
  39.  
  40. //non-concurrent version
  41. //for(int i = 0; i < SIZE; ++i){ data[i] = Func( data[i] ); }
  42.  
  43. //concurrent version
  44. QtConcurrent::mapped(data, Func);
  45.  
  46. return 0;
  47. }
To copy to clipboard, switch view to plain text mode 

I'm running it on a dual core, and the single-threaded version runs in about 0.7s, but the using QtConcurrent it takes over 30.0s. The two cores are utilized, but not at 100%.

Also, using QtConcurrent::map() I get seg-fault, and I'm not sure why.

I'm probably doing something wrong, but can anyone tell me why QtConcurrent::mapped() call slows it down so much??