A decorator to run the given method in the ThreadPoolExecutor.
558592
def run_in_executor(f):
    

    @wraps(f)
    def new_f(self, *args, **kwargs):

        if self.is_shutdown:
            return
        try:
            future = self.executor.submit(f, self, *args, **kwargs)
            future.add_done_callback(_future_completed)
        except Exception:
            log.exception("Failed to submit task to executor")

    return new_f
593129
def run(self) -> None:
        """"""
        while self._running:
            try:
                future, function = self._tx.get(timeout=0.1)
            except Empty:
                continue

            try:
                LOG.debug("executing %s", function)
                result = function()
                LOG.debug("returning %s", result)
                self._loop.call_soon_threadsafe(future.set_result, result)
            except BaseException as e:
                LOG.exception("returning exception %s", e)
                self._loop.call_soon_threadsafe(future.set_exception, e)
726564
async def _thread_coro(self, *args):
        
        return await self._loop.run_in_executor(
            self._executor, self._function, *args)
596590
def _general_multithread(func):
    

    def multithread(templates, stream, *args, **kwargs):
        with pool_boy(ThreadPool, len(stream), **kwargs) as pool:
            return _pool_normxcorr(templates, stream, pool=pool, func=func)

    return multithread
1136482
def throws(exc):
    '''
    
    '''
    if not __CHECKING__:
        return lambda f: f

    def wrap(f):
        def call(*args, **kwd):
            res = f(*args, **kwd)
            # raise UncheckedExceptionError if exc is not automatically
            # registered by a function decorated with @catches(exc);
            # otherwise do nothing
            exc_checker.throwing(exc)
            return res
        call.__name__ = f.__name__
        return call
    return wrap
699804
def run(self, target, args=()):
        
        run_event = threading.Event()
        run_event.set()
        thread = threading.Thread(target=target, args=args + (run_event, ))
        self.thread_pool.append(thread)
        self.run_events.append(run_event)
        thread.start()
375039
def wrap_threading_run(run_func):
    

    def call(self):
        execution_context.set_opencensus_full_context(
            *self._opencensus_context
        )
        return run_func(self)

    return call
761205
public static void run(final Runnable runnableWork,
            final long timeoutInSec) {
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        afterTimeout(timeoutInSec, threadPool, threadPool.submit(runnableWork));
    }
1311356
def call_sync(func):
    """"""

    @wraps(func)
    def wrapper(self, *args, **kw):
        """Wraps instance method to be called on loop thread"""

        # Just return when already on the event thread
        if self.thread.ident == get_ident():
            return func(self, *args, **kw)

        barrier = Barrier(2)
        result = None
        ex = None

        def call():
            """Calls function on loop thread"""
            nonlocal result, ex
            try:
                result = func(self, *args, **kw)
            except Exception as exc:
                ex = exc
            finally:
                barrier.wait()

        self.loop.call_soon_threadsafe(call)
        barrier.wait()
        if ex:
            raise ex or Exception("Unknown error")
        return result

    return wrapper
443472
def during(f):
    """"""
    def decorator(g):
        @wraps(g)
        def h(*args, **kargs):
            tf = Thread(target=f, args=args, kwargs=kargs)
            tf.start()
            r = g(*args, **kargs)
            tf.join()
            return r
        return h
    return decorator
21128
def run_coroutine_threadsafe(self, coro, loop=None, callback=None):
        """"""
        if not asyncio.iscoroutine(coro):
            raise TypeError("A await in coroutines. object is required")
        loop = loop or self.loop
        future = NewFuture(callback=callback)

        def callback_func():
            try:
                asyncio.futures._chain_future(NewTask(coro, loop=loop), future)
            except Exception as exc:
                if future.set_running_or_notify_cancel():
                    future.set_exception(exc)
                raise

        loop.call_soon_threadsafe(callback_func)
        return future
867545
def callToThread(method):
    
    def func_wrapped(self, *args, **kwargs):
      self.thread.execute_queue.put_nowait((threading.get_ident(), method, args, kwargs))
      return self.waitResult()
    return func_wrapped
434538
def run_in_subprocess(func, *args, **kwargs):
    """"""
    from multiprocessing import Process
    thread = Process(target=func, args=args, kwargs=kwargs)
    thread.daemon = True
    thread.start()
    return thread
133289
def run(self, func, *func_args, **func__kwargs):
        
        self._func = func
        self._func_args = func_args
        self._func_kwargs = func__kwargs
        return self
181808
def threader(group=None, name=None, daemon=True):
    
    def decorator(job):
        """
        :param job: function to be threaded
        :rtype: wrap
        """
        def wrapped_job(queue, *args, **kwargs):
            """ this function calls the decorated function
            and puts the result in a queue
            :type queue: Queue
            """
            ret = job(*args, **kwargs)
            queue.put(ret)

        def wrap(*args, **kwargs):
            """ this is the function returned from the decorator. It fires off
            wrapped_f in a new thread and returns the thread object with
            the result queue attached
            :rtype: Thread
            """
            thread = Thread(group=group, target=wrapped_job, name=name, args=args, kwargs=kwargs, daemon=daemon)
            thread.start()
            return thread
        return wrap
    return decorator
1197784
def _timed_run(self, func, distribution, args=(), kwargs={},  default=None):
        
        class InterruptableThread(threading.Thread):
            def __init__(self):
                threading.Thread.__init__(self)
                self.result = default
                self.exc_info = (None, None, None)

            def run(self):
                try:
                    self.result = func(args, **kwargs)
                except Exception as err:
                    self.exc_info = sys.exc_info()

            def suicide(self):
                raise RuntimeError('Stop has been called')

        it = InterruptableThread()
        it.start()
        started_at = datetime.now()
        it.join(self.timeout)
        ended_at = datetime.now()
        diff = ended_at - started_at

        if it.exc_info[0] is not None:  # if there were any exceptions
            a,b,c = it.exc_info
            raise Exception(a,b,c)  # communicate that to caller

        if it.isAlive():
            it.suicide()
            raise RuntimeError
        else:
            return it.result
323406
def thread_safe(method):
    

    @functools.wraps(method)
    def _locker(self, *args, **kwargs):
        assert hasattr(self, 'lock'), \
            'thread_safe decorator applied to method {0}.{1}: missing required field {0}.lock'\
            .format(self.__class__.__name__, method.__name__)

        try:
            self.lock.acquire()
            return method(self, *args, **kwargs)
        finally:
            try:
                self.lock.release()
            except:
                sys.stderr.write('Exception on releasing lock at method {0}'.format(method.__name__))
                traceback.print_exc(file=sys.stderr)

    return _locker