This main loop yields to gevent until the end, handling function calls along the way.
773410
def mainLoop(self):
        """"""
        self.greenlet = gevent.getcurrent()
        callqueue = self._callqueue
        seconds = self.seconds
        try:
            while 1:
                self._wait = 0
                now = seconds()
                if len(callqueue) > 0:
                    self._wake = delay = callqueue[0].time
                    delay -= now
                else:
                    self._wake = now + 300
                    delay = 300
                try:
                    self._wait = 1
                    try:
                        self._threadCallNotification.get(timeout=delay if delay > 0 else 0)
                    except Empty:
                        pass
                    else:
                        raise Reschedule
                    self._wait = 0
                except Reschedule:
                    if self.threadCallQueue:
                        total = len(self.threadCallQueue)
                        count = 0
                        for fn, args, kwargs in self.threadCallQueue:
                            try:
                                fn(*args, **kwargs)
                            except:
                                log.err()
                            count += 1
                            if count == total:
                                break
                        del self.threadCallQueue[:count]
                        if self.threadCallQueue:
                            self.wakeUp()
                    continue
                now = seconds()
                while 1:
                    try:
                        c = callqueue[0]
                    except IndexError:
                        break
                    if c.time <= now:
                        del callqueue[0]
                        try:
                            c()
                        except GreenletExit:
                            raise
                        except:
                            log.msg('Unexpected error in main loop.')
                            log.err()
                    else:
                        break
        except (GreenletExit, KeyboardInterrupt):
            pass
        log.msg('Main loop terminated.')
        self.fireSystemEvent('shutdown')
1214673
public void processEndOfScope(Scope scopeEnding, Iterable<Object> handlerInstances) throws Exception {
        for (Object handler : handlerInstances) {
            Handler handlerAnnotation = handler.getClass().getAnnotation(Handler.class);
            Scope scope = handlerAnnotation.scope();

            runLifecycleMethods(handler, scope, scopeEnding, true);

            //dispose handler instances with a scope which matches the scopeEnding
            if (scope == scopeEnding) {
                disposeSpringResources(handler, scopeEnding);
            }
        }
    }
742985
function() {
            // run iterator for this item
            iterator(arr[current], function(err) {
                // check for any errors with this element
                if (err) {
                    callback(err, yielded);
                } else {
                    // move onto the next element
                    current++;

                    if (current === arr.length) {
                        // all done
                        callback(null, yielded);
                    } else {
                        var now = +(new Date());

                        // check if we need to take a break at all
                        if (now > endTime) {
                            // reset start and end time
                            startTime = now;
                            endTime = startTime + workTime;

                            yielded = true;

                            // prioritize setImmediate
                            if (immediate) {
                                immediate(function() {
                                    iterate();
                                });
                            } else {
                                // if we're not doing an immediate yield, also add yield time
                                endTime += yieldTime;

                                setTimeout(function() {
                                    iterate();
                                }, yieldTime);
                            }
                        } else {
                            // work on the next item immediately
                            iterate();
                        }
                    }
                }
            });
        }
589856
def _function_handler(function, args, kwargs, pipe):
    """"""
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    result = process_execute(function, *args, **kwargs)

    send_result(pipe, result)
608777
def done(delay=nil)
        super(delay) do
          yield if block_given?
          EM.next_tick do
            run_em_hooks :amqp_after
            if AMQP.conn and not AMQP.closing
              AMQP.stop_connection do
                AMQP.cleanup_state
                finish_em_loop
              end
            else
              AMQP.cleanup_state
              finish_em_loop
            end
          end
        end
      end
527084
private void checkEnd() {
    if (ended && !closed && children == 0) {
      closed = true;
      connection.doBatchEnd(id, endArgs);
      if (endHandler != null) {
        endHandler.handle((Void) null);
      }
    }
  }
1253335
def _loop_wrapper_func(func, args, shared_mem_run, shared_mem_pause, interval, sigint, sigterm, name,
                       logging_level, conn_send, func_running, log_queue):
    
    prefix = get_identifier(name) + ' '

    global log
    log = logging.getLogger(__name__+".log_{}".format(get_identifier(name, bold=False)))
    log.setLevel(logging_level)
    log.addHandler(QueueHandler(log_queue))
  
    sys.stdout = StdoutPipe(conn_send)

    log.debug("enter wrapper_func")

    SIG_handler_Loop(sigint, sigterm, log, prefix)
    func_running.value = True
    
    error = False

    while shared_mem_run.value:
        try:
            # in pause mode, simply sleep
            if shared_mem_pause.value:
                quit_loop = False
            else:
                # if not pause mode -> call func and see what happens
                try:
                    quit_loop = func(*args)
                except LoopInterruptError:
                    raise
                except Exception as e:
                    log.error("error %s occurred in loop calling 'func(*args)'", type(e))
                    log.info("show traceback.print_exc()\n%s", traceback.format_exc())
                    error = True
                    break
 
                if quit_loop is True:
                    log.debug("loop stooped because func returned True")
                    break
 
            time.sleep(interval)
        except LoopInterruptError:
            log.debug("quit wrapper_func due to InterruptedError")
            break

    func_running.value = False
    if error:
        sys.exit(-1)
    else:
        log.debug("wrapper_func terminates gracefully")
    
    # gets rid of the following warnings
    #   Exception ignored in: <_io.FileIO name='/dev/null' mode='rb'>
    #   ResourceWarning: unclosed file <_io.TextIOWrapper name='/dev/null' mode='r' encoding='UTF-8'>
    try:
        if mp.get_start_method() == "spawn":
            sys.stdin.close()
    except AttributeError:
        pass
1018887
function end () {
      sent = true;
      // next tick it to avoid express catching runtime error in the callback
      //   getting caught by express and triggering app's error handler
      process.nextTick(function () {
        res.emit('finish');
        cb(null, res);
      });
    }
813902
def _run(self):  # pylint: disable=method-hidden
        
        try:
            self.event_stop.wait()
        except gevent.GreenletExit:  # killed without exception
            self.event_stop.set()
            gevent.killall(self.greenlets)  # kill children
            raise  # re-raise to keep killed status
        except Exception:
            self.stop()  # ensure cleanup and wait on subtasks
            raise
501923
def run(self, stdin, callbacks):
        
        assert isinstance(stdin, Input)
        assert isinstance(callbacks, EventLoopCallbacks)
        assert not self._running

        if self.closed:
            raise Exception('Event loop already closed.')

        self._running = True
        self._callbacks = callbacks

        inputstream = InputStream(callbacks.feed_key)
        current_timeout = [INPUT_TIMEOUT]  # Nonlocal

        # Create reader class.
        stdin_reader = PosixStdinReader(stdin.fileno())

        # Only attach SIGWINCH signal handler in main thread.
        # (It's not possible to attach signal handlers in other threads. In
        # that case we should rely on a the main thread to call this manually
        # instead.)
        if in_main_thread():
            ctx = call_on_sigwinch(self.received_winch)
        else:
            ctx = DummyContext()

        def read_from_stdin():
            " Read user input. "
            # Feed input text.
            data = stdin_reader.read()
            inputstream.feed(data)

            # Set timeout again.
            current_timeout[0] = INPUT_TIMEOUT

            # Quit when the input stream was closed.
            if stdin_reader.closed:
                self.stop()

        self.add_reader(stdin, read_from_stdin)
        self.add_reader(self._schedule_pipe[0], None)

        with ctx:
            while self._running:
                # Call inputhook.
                if self._inputhook_context:
                    with TimeIt() as inputhook_timer:
                        def ready(wait):
                            " True when there is input ready. The inputhook should return control. "
                            return self._ready_for_reading(current_timeout[0] if wait else 0) != []
                        self._inputhook_context.call_inputhook(ready)
                    inputhook_duration = inputhook_timer.duration
                else:
                    inputhook_duration = 0

                # Calculate remaining timeout. (The inputhook consumed some of the time.)
                if current_timeout[0] is None:
                    remaining_timeout = None
                else:
                    remaining_timeout = max(0, current_timeout[0] - inputhook_duration)

                # Wait until input is ready.
                fds = self._ready_for_reading(remaining_timeout)

                # When any of the FDs are ready. Call the appropriate callback.
                if fds:
                    # Create lists of high/low priority tasks. The main reason
                    # for this is to allow painting the UI to happen as soon as
                    # possible, but when there are many events happening, we
                    # don't want to call the UI renderer 1000x per second. If
                    # the eventloop is completely saturated with many CPU
                    # intensive tasks (like processing input/output), we say
                    # that drawing the UI can be postponed a little, to make
                    # CPU available. This will be a low priority task in that
                    # case.
                    tasks = []
                    low_priority_tasks = []
                    now = None  # Lazy load time. (Fewer system calls.)

                    for fd in fds:
                        # For the 'call_from_executor' fd, put each pending
                        # item on either the high or low priority queue.
                        if fd == self._schedule_pipe[0]:
                            for c, max_postpone_until in self._calls_from_executor:
                                if max_postpone_until is None:
                                    # Execute now.
                                    tasks.append(c)
                                else:
                                    # Execute soon, if `max_postpone_until` is in the future.
                                    now = now or _now()
                                    if max_postpone_until < now:
                                        tasks.append(c)
                                    else:
                                        low_priority_tasks.append((c, max_postpone_until))
                            self._calls_from_executor = []

                            # Flush all the pipe content.
                            os.read(self._schedule_pipe[0], 1024)
                        else:
                            handler = self._read_fds.get(fd)
                            if handler:
                                tasks.append(handler)

                    # When there are high priority tasks, run all these.
                    # Schedule low priority tasks for the next iteration.
                    if tasks:
                        for t in tasks:
                            t()

                        # Postpone low priority tasks.
                        for t, max_postpone_until in low_priority_tasks:
                            self.call_from_executor(t, _max_postpone_until=max_postpone_until)
                    else:
                        # Currently there are only low priority tasks -> run them right now.
                        for t, _ in low_priority_tasks:
                            t()

                else:
                    # Flush all pending keys on a timeout. (This is most
                    # important to flush the vt100 'Escape' key early when
                    # nothing else follows.)
                    inputstream.flush()

                    # Fire input timeout event.
                    callbacks.input_timeout()
                    current_timeout[0] = None

        self.remove_reader(stdin)
        self.remove_reader(self._schedule_pipe[0])

        self._callbacks = None
1269813
function finisher(error, output, callback)
{
  // signal end of the stream
  // only for successfully finished streams
  if (!error)
  {
    this.push(null);
  }

  // back to original track
  callback(error, output);
}
974842
def call_inputhook(self, input_is_ready_func):
        
        self._input_is_ready = input_is_ready_func

        # Start thread that activates this pipe when there is input to process.
        def thread():
            input_is_ready_func(wait=True)
            os.write(self._w, b'x')

        threading.Thread(target=thread).start()

        # Call inputhook.
        self.inputhook(self)

        # Flush the read end of the pipe.
        try:
            # Before calling 'os.read', call select.select. This is required
            # when the gevent monkey patch has been applied. 'os.read' is never
            # monkey patched and won't be cooperative, so that would block all
            # other select() calls otherwise.
            # See: http://www.gevent.org/gevent.os.html

            # Note: On Windows, this is apparently not an issue.
            #       However, if we would ever want to add a select call, it
            #       should use `windll.kernel32.WaitForMultipleObjects`,
            #       because `select.select` can't wait for a pipe on Windows.
            if not is_windows():
                select_fds([self._r], timeout=None)

            os.read(self._r, 1024)
        except OSError:
            # This happens when the window resizes and a SIGWINCH was received.
            # We get 'Error: [Errno 4] Interrupted system call'
            # Just ignore.
            pass
        self._input_is_ready = None
1198396
def _run_done_callbacks(self):
        ''' 
        '''
        with self._callbacks_lock:
            for callback in self._done_callbacks:
                try:
                    callback()
                # We do not want a callback interrupting the process, especially
                # in the failure cleanups. So log and catch, the excpetion.
                except Exception as ex:
                    logger.error("Exception: %s" % str(ex))
                    logger.error("Exception raised in %s." % callback, exc_info=True)

            self._done_callbacks = []
450812
function utilCallbackAfterPromise(self, func, args, cb) {
	args = Array.prototype.slice.apply(args);
	let lastarg = args.pop();
	if(!cb) cb = lastarg;
	func.apply(self, args).then(res => {
		try {
			cb(null, res);
		} catch(e) {
			process.nextTick(() => { throw e });
		}
	}).catch((err) => {
		try {
			cb(err);
		} catch(e) {
			process.nextTick(() => { throw e });
		}
	});
}
1201718
function callHandler(fn, req, res, next) {
    let context = new Context(req, res);
    if (utils.isGeneratorFunction(fn)) {
        co(fn).call(context, function (err) {
            if (err || !res.terminated) {
                next(err);
            }
        });
    } else {
        fn.call(context);
        if (!res.terminated) {
            next();
        }
    }
}
541012
def _execute(self):
        
        for call in (self.prepare, self.process, self.on_finish):
            self.logger.debug('Invoking %r', call)
            result = call()
            if concurrent.is_future(result):
                yield result
100424
def _spawn(self, func: Callable, *args, **kwargs) -> gevent.Greenlet:
        

        def on_success(greenlet):
            if greenlet in self.greenlets:
                self.greenlets.remove(greenlet)

        greenlet = gevent.spawn(func, *args, **kwargs)
        greenlet.link_exception(self.on_error)
        greenlet.link_value(on_success)
        self.greenlets.append(greenlet)
        return greenlet