title: Why does my context manager __exit__ function run before the computation isn't finished?
body: <p>The <strong>exit</strong> function of my custom context manager seemingly runs before the computation is done. My context manager is meant to simplify writing concurrent/parallel code. Here is my context manager code:</p>
  
  <pre><code>import time
  from multiprocessing.dummy import Pool, cpu_count
  
  class managed_pool:
      '''Simple context manager for multiprocessing.dummy.Pool'''
      def __init__(self, msg):
          self.msg = msg
      def __enter__(self):
          cores = cpu_count()
          print 'start concurrent ({0} cores): {1}'.format(cores, self.msg)
          self.start = time.time()
          self.pool = Pool(cores)
          return self.pool
      def __exit__(self, type_, value, traceback):
          print 'end concurrent:', self.msg
          print 'time:', time.time() - self.start
          self.pool.close()
          self.pool.join()
  </code></pre>
  
  <p>I've already tried this script with <code>multiprocessing.Pool</code> instead of <code>multiprocessing.dummy.Pool</code> and it seems to fail all the time.</p>
  
  <p>Here is an example of using the context manager:</p>
  
  <pre><code>def read_engine_files(f):
      engine_input = engineInput()
      with open(f, 'rb') as f:
          engine_input.parse_from_string(f.read())
      return engine_input
  
  with managed_pool('load input files') as pool:
      data = pool.map(read_engine_files, files)
  </code></pre>
  
  <p>So, inside of <code>read_engine_files</code> I print the name of the file. You'll notice in the <code>__exit__</code> function that I also print out when the computation is done and how long it took. But when viewing stdout the <code>__exit__</code> message appears way before the computation finished. Like, minutes before the computation is done. But <code>htop</code> says all of my cores are still being used. Here's an example of the output</p>
  
  <pre><code>start concurrent (4 cores): load engine input files
  file1.pbin
  file2.pbin
  ...
  file16.pbin
  end concurrent: load engine input files
  time: 246.43829298
  file17.pbin
  ...
  file45.pbin
  </code></pre>
  
  <p>Why is <code>__exit__</code> being called so early?</p>