def thunkify(thread_name=None, daemon=True, default_func=None):
    '''Make a function immediately return a function of no args which, when called,
    waits for the result, which will start being processed in another thread.
    Taken from https://wiki.python.org/moin/PythonDecoratorLibrary.
    '''
    def actual_decorator(f):
        @functools.wraps(f)
        def thunked(*args, **kwargs):
            result = [None]
            exc = [False, None]  # has exception?, exception info
#             wait_event = threading.Event()

            def worker_func():
                try:
                    func_result = f(*args, **kwargs)
                    result[0] = func_result
                except Exception:
                    exc[0] = True
                    exc[1] = sys.exc_info()
                    logging.error("%s has thrown an exception:\n%s", thread_name, traceback.format_exc())
#                 finally:
#                     wait_event.set()

            worker_thread = Thread(target=worker_func, name=thread_name if thread_name else None)
            worker_thread.daemon = daemon

            def thunk(timeout=None):
                # avoid blocking MainThread
                start_time = time()
                while True:
                    worker_thread.join(timeout=0.1)
                    if (timeout and timeout < time() - start_time) or not worker_thread.is_alive():
                        break
#                 worker_thread.join(timeout=timeout)
#                 wait_event.wait()
                if worker_thread.is_alive():
                    if default_func is None:
                        return
                    else:
                        return default_func()
                if exc[0]:
                    raise exc[1][0], exc[1][1], exc[1][2]
                return result[0]

            worker_thread.start()
#             threading.Thread(target=worker_func, name=thread_name if thread_name else None).start()
            return thunk
        return thunked
    return actual_decorator