The primary run loop of the kqueue event processor.
553427
@Override
   public void run()
   {
      try {
         startBarrier.await();

         int idleCount = 0;
         while (!isRunning.compareAndSet(idleCount > LINGER_ITERATIONS && deadPool.isEmpty() && completionKeyToProcessMap.isEmpty(), false)) {
            idleCount = (!shutdown && process()) ? 0 : (idleCount + 1);
         }
      }
      catch (Exception e) {
         // TODO: how to handle this error?
         e.printStackTrace();
         isRunning.set(false);
      }
   }
1307303
function main()
{
	aqParseOptions();

	aq_queuename = 'amqpsnoop.' + Math.random() * 10000000;
	aq_amqp = mod_amqp.createConnection(aq_broker);
	aq_amqp.on('ready', function () {
		aq_queue = aq_amqp.queue(aq_queuename,
		    { exclusive: true }, function () {
			aq_queue.bind(aq_exchange, aq_routekey);
			aq_queue.subscribe(aqReceiveMessage);
		    });
	});
}
427500
def _run_queued_callbacks(self):
        '''  '''
        for callback in self._queued_callbacks:
            try:
                callback()
            except Exception as ex:
                logger.error("Exception: %s" % str(ex))
1234900
function(eventName, cpuNumber, pid, ts, eventBase) {
      var event = workqueueExecuteStartRE.exec(eventBase.details);
      if (!event)
        return false;

      var kthread = this.importer.getOrCreateKernelThread(eventBase.threadName,
          pid, pid);
      kthread.openSliceTS = ts;
      kthread.openSlice = event[2];
      return true;
    }
1321725
void transformAndQueue(T event, long systemCurrentTimeMillis) {
        // if you're super unlucky, this blows up the stack
        if (rand.nextDouble() < 0.05) {
            // duplicate this message (note recursion means maybe more than duped)
            transformAndQueue(event, systemCurrentTimeMillis);
        }

        long delayms = nextZipfDelay();
        delayed.add(systemCurrentTimeMillis + delayms, event);
    }
431281
def run(self):
        '''
        
        '''
        salt.utils.process.appendproctitle(self.__class__.__name__)
        self.event = get_event('master', opts=self.opts, listen=True)
        events = self.event.iter_events(full=True)
        self.event.fire_event({}, 'salt/event_listen/start')
        try:
            for event in events:
                if event['tag'] == 'salt/event/exit':
                    self.stop = True
                if self._filter(event):
                    self.event_queue.append(event)
                if len(self.event_queue) >= self.event_return_queue:
                    self.flush_events()
                if self.stop:
                    break
        finally:  # flush all we have at this moment
            if self.event_queue:
                self.flush_events()
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()
371900
void enqueue(Runnable runnable, boolean flush) {
    queue.add(new RunnableCommand(runnable));
    if (flush) {
      scheduleFlush();
    }
  }
470276
void processTedQueue() {
		int totalProcessing = context.taskManager.calcWaitingTaskCountInAllChannels();
		if (totalProcessing >= TaskManager.LIMIT_TOTAL_WAIT_TASKS) {
			logger.warn("Total size of waiting tasks ({}) already exceeded limit ({}), skip this iteration (2)", totalProcessing, TaskManager.LIMIT_TOTAL_WAIT_TASKS);
			return;
		}
		Channel channel = context.registry.getChannelOrMain(Model.CHANNEL_QUEUE);
		int maxTask = context.taskManager.calcChannelBufferFree(channel);
		maxTask = Math.min(maxTask, 50);
		Map<String, Integer> channelSizes = new HashMap<String, Integer>();
		channelSizes.put(Model.CHANNEL_QUEUE, maxTask);
		List<TaskRec> heads = tedDao.reserveTaskPortion(channelSizes);
		if (heads.isEmpty())
			return;

		for (final TaskRec head : heads) {
			logger.debug("exec eventQueue for '{}', headTaskId={}", head.key1, head.taskId);
			channel.workers.execute(new TedRunnable(head) {
				@Override
				public void run() {
					processEventQueue(head);
				}
			});
		}
	}
834572
function(event, queue, visited, flowEvents) {
      var stopFollowing = false;
      var inputAck = false;

      event.iterateAllSubsequentSlices(function(slice) {
        if (stopFollowing)
          return;

        // Do not follow TaskQueueManager::RunTask because it causes
        // many false events to be included.
        if (slice.title === 'TaskQueueManager::RunTask')
          return;

        // Do not follow ScheduledActionSendBeginMainFrame because the real
        // main thread BeginMainFrame is already traced by LatencyInfo flow.
        if (slice.title === 'ThreadProxy::ScheduledActionSendBeginMainFrame')
          return;

        // Do not follow ScheduleBeginImplFrameDeadline that triggers an
        // OnBeginImplFrameDeadline that is tracked by another LatencyInfo.
        if (slice.title === 'Scheduler::ScheduleBeginImplFrameDeadline') {
          if (this.triggerOtherInputs(slice, flowEvents))
            return;
        }

        // Do not follow PostComposite that triggers CompositeImmediately
        // that is tracked by another LatencyInfo.
        if (slice.title === 'CompositorImpl::PostComposite') {
          if (this.triggerOtherInputs(slice, flowEvents))
            return;
        }

        // Stop following the rest of the current slice hierarchy if
        // FilterAndSendWebInputEvent occurs after ProcessInputEventAck.
        if (slice.title === 'InputRouterImpl::ProcessInputEventAck')
          inputAck = true;
        if (inputAck &&
            slice.title === 'InputRouterImpl::FilterAndSendWebInputEvent')
          stopFollowing = true;

        this.followCurrentSlice(slice, queue, visited);
      }, this);
    }
572960
def main():
    """"""
    # Helper method so that the coroutine exits cleanly if an exception
    # happens (which would leave resources dangling)
    async def _run_application(loop):
        try:
            return await cli_handler(loop)

        except KeyboardInterrupt:
            pass  # User pressed Ctrl+C, just ignore it

        except SystemExit:
            pass  # sys.exit() was used - do nothing

        except:  # pylint: disable=bare-except  # noqa
            import traceback

            traceback.print_exc(file=sys.stderr)
            sys.stderr.writelines(
                '\n>>> An error occurred, full stack trace above\n')

        return 1

    try:
        loop = asyncio.get_event_loop()
        return loop.run_until_complete(_run_application(loop))
    except KeyboardInterrupt:
        pass

    return 1
381136
def run_iteration(self):
        '''
        '''

        self._employer_phase()
        self._calc_probability()
        self._onlooker_phase()
        self._check_positions()
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')
1097246
def run(self):
        
        self._stop = False
        while not self._stop:
            have_sources = self._timers or self._readers or self._writers
            if not self._processor.pending and not have_sources:
                break
            events = QEventLoop.AllEvents
            if not self._processor.pending:
                events |= QEventLoop.WaitForMoreEvents
            self._qapp.processEvents(events)
            if self._processor.pending:
                self._processor.run()
193771
def _read_select_kqueue(k_queue):
        
        npipes = len(NonBlockingStreamReader._streams)
        # Create list of kevent objects
        # pylint: disable=no-member
        kevents = [select.kevent(s.stream.fileno(),
                                 filter=select.KQ_FILTER_READ,
                                 flags=select.KQ_EV_ADD | select.KQ_EV_ENABLE)
                   for s in NonBlockingStreamReader._streams]
        while NonBlockingStreamReader._run_flag:
            events = k_queue.control(kevents, npipes, 0.5)  # Wake up twice in second
            for event in events:
                if event.filter == select.KQ_FILTER_READ:  # pylint: disable=no-member
                    NonBlockingStreamReader._read_fd(event.ident)
            # Check if new pipes added.
            if npipes != len(NonBlockingStreamReader._streams):
                return
1207897
def run(self):
        """"""
        input = self._consume()
        put_item = self._que_out.put
        
        try:
            if input is None: # producer
                res = self._callable(*self._args, **self._kwargs)
            else:
                res = self._callable(input, *self._args, **self._kwargs)
            if res != None:
                for item in res:
                    put_item(item)

        except Exception as e:
            # we catch an error, we send on the error que, we consume the input and we exit
            # consuming the input queue avoid to keep running processes before exiting with
            # errors
            self._que_err.put((self.name, e))
            if input is not None:
                for i in input:
                    pass
            raise

        finally:
            for i in range(self._num_followers):
                put_item(EXIT)
            self._que_err.put(EXIT)
960210
public void run() {
        int length;
        char cs[] = new char[256];
        int ioErrorCount = 0;
        Reader reader = pair.getReader();

        logger.trace("Starting primary loop");
        while ( !stopRequested && !foundEOF && ioErrorCount < 4) {
            try {
                logger.trace("Checking ready");
                boolean ready = false;
                try {
                    ready = reader.ready(); // will not block
                    if( reader.markSupported() ) logger.trace("Mark Supported");
                } catch(Exception ioe) {
                    // The Pipe most likely closed on us.
                    logger.debug("Exception in PollingConsumer: " + ioe);
                    foundEOF = true;
                    break;
                }

                //if( !ready ) { ready = true; log.fine("Faking ready"); }

                if ( ready ) {
                    logger.trace("Is Ready");


                    // don't modify the buffer while processing is happening
                    // written as while loop to prevent spurious interrupts
                    synchronized(this) {
                        while( callerProcessing.booleanValue() ) {
                            logger.trace("Waiting for caller to finish");
                            try {
                                wait();
                            } catch(InterruptedException ie) {
                                logger.trace("Woken up early");
                                continue;
                            }
                        }

                        logger.trace("About to wait for buffer lock");
                        synchronized(buffer) {
                            length = reader.read(cs);

                            if( length == -1 ) { //EOF
                                logger.trace("Found the EOF");
                                logger.trace("Current buffer: " + buffer.toString() );
                                foundEOF = true;
                                dirtyBuffer = true;
                                break;
                            }

                            String print = new String(cs, 0, length);
                            print = print.replaceAll("\n", "\\\\n");
                            print = print.replaceAll("\r", "\\\\r");
                            logger.trace("Appending >>>" + print + "<<<");
                            buffer.append( cs, 0, length ); // thread safe

                            logger.trace("Current Buffer: " + buffer.toString() );
                            dirtyBuffer = true;

                            /**
                             * TODO Trim down buffer.  This current method won't work if a resume comes in, since it's offset
                             * will be invalid once this delete method runs
                             *
                             * // since we only added one char, we should only have to remove one
                             * if( buffer.length() > BUFFERMAX )
                             * buffer.delete(0, BUFFERMAX - buffer.length() );
                             */

                            logger.trace("Waking up who ever if listening");
                            buffer.notify(); // seeing that we read something, wait people up

                            // We explicitly call this after appending to the
                            // buffer, just in case one of the BufferChangeLoggers
                            // accidentally modifies the character buffer.
                            notifyBufferChange(cs, length);
                        }
                    }

                } else {
                    logger.trace("Not Ready, sleeping");
                    try { Thread.sleep(500); } catch(InterruptedException ie) { }
                    logger.trace("Done sleeping");
                    //continue;
                }
            }catch(IOException ioe) {
                logger.warn("Exception in loop body: " + ioe);
                ioErrorCount++;
                //continue;
            }
        } // end while loop


        synchronized(buffer) {
            buffer.notify();
        }
        if( stopRequested ) {
            logger.debug("Stop Requested");
            pair.close();
        }
        if ( foundEOF )
            logger.debug("Found EOF to stop while loop");
        if( ioErrorCount >= 4 )
            logger.debug("ioErrorCount at " + ioErrorCount );
        logger.trace("Leaving primary loop");
    }