title: Problem using pthread to utilize multiple cores
body: <p>I’m developing a Ray Tracer in C++ using SDL and Pthread. I’m having issues making my program utilize two cores. The threads work, but they don’t use both cores to 100%. To interface SDL I write directly to it's memory, SDL_Surface.pixels, so I assume that it can't be SDL locking me.</p>
  
  <p>My thread function looks like this:</p>
  
  <pre><code>void* renderLines(void* pArg){
  while(true){
      //Synchronize
      pthread_mutex_lock(&amp;frame_mutex);
      pthread_cond_wait(&amp;frame_cond, &amp;frame_mutex);
      pthread_mutex_unlock(&amp;frame_mutex);
  
      renderLinesArgs* arg = (renderLinesArgs*)pArg;
      for(int y = arg-&gt;y1; y &lt; arg-&gt;y2; y++){
          for(int x = 0; x &lt; arg-&gt;width; x++){
              Color C = arg-&gt;scene-&gt;renderPixel(x, y);
              putPixel(arg-&gt;screen, x, y, C);
          }
      }
  
      sem_post(&amp;frame_rendered);
      }
  }
  </code></pre>
  
  <p>Note: scene->renderPixel is const, so I assume both threads can read from the same memory.
  I have two worker threads doing this, in my main loop I make these work using:</p>
  
  <pre><code>//Signal a new frame
  pthread_mutex_lock(&amp;frame_mutex);
  pthread_cond_broadcast(&amp;frame_cond);
  pthread_mutex_unlock(&amp;frame_mutex);
  
  //Wait for workers to be done
  sem_wait(&amp;frame_rendered);
  sem_wait(&amp;frame_rendered);
  
  //Unlock SDL surface and flip it...
  </code></pre>
  
  <p>Note: I've also tried creating and joining the threads instead of synchronizing them.
  I compile this with "-lpthread -D_POSIX_PTHREAD_SEMANTICS -pthread" and gcc does not complain.</p>
  
  <p>My problem is best illustrated using a graph of the CPU usage during execution:
  <a href="https://i.stack.imgur.com/DFLFg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DFLFg.png" alt="CPU usage during execution."></a><br>
  <sub>(source: <a href="http://jopsen.dk/downloads/processor_usage.png" rel="nofollow noreferrer">jopsen.dk</a>)</sub>  </p>
  
  <p>As can be seen from the graph my program only uses one core at a time, then switching between the two every once in a while, but it doesn't drive both to 100% ever.
  What in the world have I done wrong? I'm not using any mutex or semaphors in scene.
  What can I do to find the bug?</p>
  
  <p>Also if I put while(true) around scene->renderPixel() I can push both cores to 100%. So I've suspected that this is caused by overhead, but I only synchronize every 0.5 second (e.g. FPS: 0.5), given a complex scene.
  I realize it might not be easy to tell me what my bug is, but an approach to debugging this would be great too... I haven't played with pthreads before...</p>
  
  <p>Also, can this be a hardware or kernel issue, my kernel is:</p>
  
  <pre><code>$uname -a
  Linux jopsen-laptop 2.6.27-14-generic #1 SMP Fri Mar 13 18:00:20 UTC 2009 i686 GNU/Linux
  </code></pre>
  
  <p>Note:</p>