Call `func` in background thread, and then call `callback` in Gtk main thread.

    If error occurs in `func`, error will keep the traceback and passed to
    `callback` as second parameter. Always check `error` is not None.
335459
def async_call(func, *args, callback=None):
    '''
    '''
    def do_call():
        result = None
        error = None

        try:
            result = func(*args)
        except Exception:
            error = traceback.format_exc()
            logger.error(error)
        if callback:
            GLib.idle_add(callback, result, error)

    thread = threading.Thread(target=do_call)
    thread.daemon = True
    thread.start()
1306232
def _enable_thread_pool(func):
    

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        self = args[0]
        if self.enable_thread_pool and hasattr(self, 'thread_pool'):
            future = self.thread_pool.submit(func, *args, **kwargs)
            is_async = kwargs.get('is_async')
            if is_async is None or not is_async:
                timeout = kwargs.get('timeout')
                if timeout is None:
                    timeout = 2
                try:
                    result = future.result(timeout=timeout)
                except TimeoutError as e:
                    self.logger.exception(e)
                    result = None
                return result
            return future
        else:
            return func(*args, **kwargs)

    return wrapper
53457
function callbackOnce(err, arg) {
            var cb = callback;
            callback = null;
            if (cb) { cb(err, arg); }
        }
867568
def call(self, name: str, *args, **kwargs):
        ''''''
        if self._event_dispatcher is not None:
            self._event_dispatcher.notify(name, *args, **kwargs)

        if self._callbacks[name]:
            return self._callbacks[name](*args, **kwargs)
        else:
            raise HookDisconnected('No callback is connected.')
764845
def on_call(self, node):
        """"""
        #  ('func', 'args', 'keywords'. Py<3.5 has 'starargs' and 'kwargs' too)
        func = self.run(node.func)
        if not hasattr(func, '__call__') and not isinstance(func, type):
            msg = "'%s' is not callable!!" % (func)
            self.raise_exception(node, exc=TypeError, msg=msg)

        args = [self.run(targ) for targ in node.args]
        starargs = getattr(node, 'starargs', None)
        if starargs is not None:
            args = args + self.run(starargs)

        keywords = {}
        if six.PY3 and func == print:
            keywords['file'] = self.writer

        for key in node.keywords:
            if not isinstance(key, ast.keyword):
                msg = "keyword error in function call '%s'" % (func)
                self.raise_exception(node, msg=msg)
            keywords[key.arg] = self.run(key.value)

        kwargs = getattr(node, 'kwargs', None)
        if kwargs is not None:
            keywords.update(self.run(kwargs))

        try:
            return func(*args, **keywords)
        except Exception as ex:
            self.raise_exception(
                node, msg="Error running function call '%s' with args %s and "
                "kwargs %s: %s" % (func.__name__, args, keywords, ex))
753425
def callback(self):
        """"""
        try:
            return self._callback()
        except:
            # All exceptions raised here will trigger the shutdown!
            s = straceback()
            self.exceptions.append(s)

            # This is useful when debugging
            #try:
            #    print("Exception in callback, will cancel all tasks")
            #    for task in self.flow.iflat_tasks():
            #        task.cancel()
            #except Exception:
            #    pass

            self.shutdown(msg="Exception raised in callback!\n" + s)
440282
function(err, result) {
      if (err && !util.isError(err)) {
        err = new Error(err);
      }
      if (callback) callback(err, result);
    }
1021523
def threaded(func):
    

    def dec(self, *args, **kwargs):
        thread.start_new_thread(func, (self, ) + args, kwargs)

    return dec
149496
def communicator(func):
    ''''''
    def _call(queue, args, kwargs):
        '''called with [queue, args, kwargs] as first optional arg'''
        kwargs['queue'] = queue
        ret = None
        try:
            ret = func(*args, **kwargs)
            queue.put('END')
        except KeyboardInterrupt as ex:
            trace = traceback.format_exc()
            queue.put('KEYBOARDINT')
            queue.put('Keyboard interrupt')
            queue.put('{0}\n{1}\n'.format(ex, trace))
        except Exception as ex:
            trace = traceback.format_exc()
            queue.put('ERROR')
            queue.put('Exception')
            queue.put('{0}\n{1}\n'.format(ex, trace))
        except SystemExit as ex:
            trace = traceback.format_exc()
            queue.put('ERROR')
            queue.put('System exit')
            queue.put('{0}\n{1}\n'.format(ex, trace))
        return ret
    return _call
676486
def _execute_callback_async(self, callback, data):
        
        if asyncio.iscoroutine(callback):
            asyncio.ensure_future(
                callback(rtm_client=self, web_client=self._web_client, data=data)
            )
        else:
            asyncio.ensure_future(
                asyncio.coroutine(callback)(
                    rtm_client=self, web_client=self._web_client, data=data
                )
            )
976385
def initialize_check_thread(self, check_func):
        # type: (_MultiprocessOffload, function) -> None
        
        self._check_thread = threading.Thread(target=check_func)
        self._check_thread.start()
770129
def run_on_new_thread(func, daemon=True):
    
    f = concurrent.futures.Future()
    def wrapper():
        if not f.set_running_or_notify_cancel():
            return
        try:
            f.set_result(func())
        except Exception as e:
            f.set_exception(e)
    t = threading.Thread(target=wrapper)
    t.daemon = daemon
    t.start()
    return f
957229
def _async_callable(func):
    """"""
    if isinstance(func, types.CoroutineType):

        return func

    @functools.wraps(func)
    async def _async_def_wrapper(*args, **kwargs):
        """Wrap a a sync callable in an async def."""
        return func(*args, **kwargs)

    return _async_def_wrapper
158488
def threadsafe_call(self, fn, *args, **kwargs):
        """"""
        def handler():
            try:
                fn(*args, **kwargs)
            except Exception:
                warn("error caught while excecuting async callback\n%s\n",
                     format_exc())

        def greenlet_wrapper():
            gr = greenlet.greenlet(handler)
            gr.switch()

        self._async_session.threadsafe_call(greenlet_wrapper)
1216558
def _threaded_callback(callback, *args):
    
    t = Thread(target=callback, args=args)
    t.daemon = True
    t.start()
150487
function invokeGuardedCallback(name, func, a) {
  try {
    func(a);
  } catch (x) {
    if (caughtError === null) {
      caughtError = x;
    }
  }
}
67380
def set_call_back(self, func):

        """"""

        self.timer.add_callback(func)
        self.timer.start()