new_contents: #!/usr/bin/env python
  # -*- coding: utf-8 -*- 
  
  #
  # Copyright 2017 Guenter Bartsch
  #
  # This program is free software: you can redistribute it and/or modify
  # it under the terms of the GNU Lesser General Public License as published by
  # the Free Software Foundation, either version 3 of the License, or
  # (at your option) any later version.
  #
  # This program is distributed in the hope that it will be useful,
  # but WITHOUT ANY WARRANTY; without even the implied warranty of
  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  # GNU Lesser General Public License for more details.
  # 
  # You should have received a copy of the GNU Lesser General Public License
  # along with this program.  If not, see <http://www.gnu.org/licenses/>.
  #
  #
  # A simple thread pool implementation
  #
  
  from Queue import Queue
  from threading import Thread, Lock
  
  class Worker(Thread):
      """Thread executing tasks from a given tasks queue"""
      def __init__(self, tasks):
          Thread.__init__(self)
          self.tasks = tasks
          self.daemon = True
          self.start()
  
      def run(self):
          while True:
              func, args, kargs = self.tasks.get()
              try:
                  func(*args, **kargs)
              except Exception, e:
                  traceback.print_exc()
              finally:
                  self.tasks.task_done()
  
  class ThreadPool:
      """Pool of threads consuming tasks from a queue"""
      def __init__(self, num_threads):
          self.tasks = Queue(num_threads)
          self.terminal_lock = Lock()
          for _ in range(num_threads): Worker(self.tasks)
  
      def add_task(self, func, *args, **kargs):
          """Add a task to the queue"""
          self.tasks.put((func, args, kargs))
  
      def wait_completion(self):
          """Wait for completion of all the tasks in the queue"""
          self.tasks.join()
  
      def print_synced(self, s):
          self.terminal_lock.acquire()
          print s
          self.terminal_lock.release()
  
  
subject: add threadpool implementation