title: Multithreaded Python script taking longer than non-threaded script
body: <p>Disclaimer:  I'm pretty terrible with multithreading, so it's entirely possible I'm doing something wrong.  </p>
  
  <p>I've written a very basic raytracer in Python, and I was looking for ways to possibly speed it up.  Multithreading seemed like an option, so I decided to try it out.  However, while the original script took ~85 seconds to process my sample scene, the multithreaded script ends up taking ~125 seconds, which seems pretty unintuitive.</p>
  
  <p>Here's what the original looks like (I'm not going to copy the drawing logic and stuff in here. If someone thinks that would be needed to figure out the problem, I'll go ahead and put it back in):</p>
  
  <pre><code>def getPixelColor(x, y, scene):
      &lt;some raytracing code&gt;
  
  def draw(outputFile, scene):
      &lt;some file handling code&gt;
      for y in range(scene.getHeight()):
          for x in range(scene.getWidth()):
              pixelColor = getPixelColor(x, y, scene)
              &lt;write pixelColor to image file&gt;
  
  if __name__ == "__main__":
      scene = readScene()
      draw(scene)
  </code></pre>
  
  <p>And here's the multithreaded version:</p>
  
  <pre><code>import threading
  import Queue
  
  q = Queue.Queue()
  pixelDict = dict()
  
  class DrawThread(threading.Thread):
      def __init__(self, scene):
          self.scene = scene
          threading.Thread.__init__(self)
  
      def run(self):
          while True:
          try:
              n, x, y = q.get_nowait()
          except Queue.Empty:
              break
          pixelDict[n] = getPixelColor(x, y, self.scene)
          q.task_done()
  
      def getPixelColor(x, y, scene):
          &lt;some raytracing code&gt;
  
  def draw(outputFile, scene):
      &lt;some file handling code&gt;
      n = 0
      work_threads = 4
      for y in range(scene.getHeight()):
          for x in range(scene.getWidth()):
              q.put_nowait((n, x, y))
              n += 1
      for i in range(work_threads):
          t = DrawThread(scene)
          t.start()
      q.join()
      for i in range(n)
          pixelColor = pixelDict[i]
          &lt;write pixelColor to image file&gt;
  
  if __name__ == "__main__":
      scene = readScene()
      draw(scene)
  </code></pre>
  
  <p>Is there something obvious that I'm doing wrong?  Or am I incorrect in assuming that multithreading would give a speed boost to a process like this?</p>