title: Generating mandelbrot images in c++ using multithreading. No speedup?
body: <p>So I posted a similar question to this earlier, but I didn't post enough code to get the help I needed. Even if I went back and added that code now, I don't think it would be noticed because the question is old and "answered". So here's my issue:</p>
  
  <p>I'm trying to generate a section of the mandelbrot fractal. I can generate it fine, but when I add more cores, no matter how large the problem size is, the extra threads generate no speedup. I am completely new to multithreading and it's probably just something small I'm missing. Anyway, here are the functions that generate the fractal:</p>
  
  <pre><code>void mandelbrot_all(std::vector&lt;std::vector&lt;int&gt;&gt;&amp; pixels, int X, int Y, int numThreads) {
      using namespace std;
  
      vector&lt;thread&gt; threads (numThreads);
      int rowsPerThread = Y/numThreads;
      mutex m;
  
      for(int i=0; i&lt;numThreads; i++) {
          threads[i] = thread ([&amp;](){
              vector&lt;int&gt; row;
              for(int j=(i-1)*rowsPerThread; j&lt;i*rowsPerThread; j++) {
                  row = mandelbrot_row(j, X, Y);
                  {
                      lock_guard&lt;mutex&gt; lock(m);
                      pixels[j] = row;
                  }
              }
          });
      }
      for(int i=0; i&lt;numThreads; i++) {
          threads[i].join();
      }
  }
  
  std::vector&lt;int&gt; mandelbrot_row(int rowNum, int topX, int topY) {
      std::vector&lt;int&gt; row (topX);
      for(int i=0; i&lt;topX; i++) {
          row[i] = mandelbrotOne(i, rowNum, topX, topY);
      }
      return row;
  }
  
  int mandelbrotOne(int currX, int currY, int X, int Y) { //code adapted from http://en.wikipedia.org/wiki/Mandelbrot_set
      double x0 = convert(X, currX, true);
      double y0 = convert(Y, currY, false);
      double x = 0.0;
      double y = 0.0;
      double xtemp;
      int iteration = 0;
      int max_iteration = 255;
      while ( x*x + y*y &lt; 2*2  &amp;&amp;  iteration &lt; max_iteration) {
          xtemp = x*x - y*y + x0;
          y = 2*x*y + y0;
          x = xtemp;
          ++iteration;
      }
      return iteration;
  }
  </code></pre>
  
  <p>mandelbrot_all is passed a vector to hold the pixels, the maximum X and Y of the vector, and the number of threads to use, which is taken from the command line when the program is run. It attempts to split the work by row among multiple threads. Unfortunately, it seems that even if that is what it's doing, it's not making it any faster. If you need more details, feel free to ask and I will do my best to provide them.</p>
  
  <p>Thanks in advance for the help.</p>
  
  <p>Edit: reserved vectors in advance
  Edit 2: ran this code with problem size 9600x7200 on a quad core laptop. It took an average of 36590000 cycles for one thread (over 5 runs) and 55142000 cycles for four threads. </p>