The main routine for a thread's work.

    The thread pulls tasks from the manager's task queue and executes
    them until it encounters a task with a function that is None.
768801
def run(self):
    
    try:
      while True:
        aFunction, arguments = self.manager.taskQueue.get()
        if aFunction is None:
          break
        aFunction(arguments)
    except KeyboardInterrupt:
      import thread
      print >>sys.stderr, "%s caught KeyboardInterrupt" % threading.currentThread().getName()
      thread.interrupt_main()
    except Exception, x:
      print >>sys.stderr, "Something BAD happened in %s:" % threading.currentThread().getName()
      traceback.print_exc(file=sys.stderr)
      print >>sys.stderr, x
185219
function WorkingQueue(concurrency) {
    // Parallelization degree, if not mentioned use 64
    // Don't forget that we are in a SINGLE-threaded process
    // All we want it to somewhat limit the number of simultaneous
    // I/O requests
    concurrency = concurrency || 64;


    // The queue contains tuples :
    // [job, arg1, arg2, arg3...]
    var queue = [];
    var workers = 0;
    var onceDoneCallbacks = [];
    var held = false;
    var added = false;

    // This function launches a new worker, if possible
    // It returns true if a new worker was launched, false otherwise.
    function _go() {
        if(workers < concurrency) {
            var job = queue.shift();
            if(job !== undefined) {
                var worker = job.shift();
                job.push(over);
                workers++;
                process.nextTick(function nextTickWorker() {
                    worker.apply(null, job);
                });
                return true;
            }
        }
        return false;
    }

    // This function is passed to each job, it must be called
    // when the job is done.
    function over() {
        workers--;

        if(!held) { _go(); }

        checkDone();
    }

    function checkDone() {
        if(queue.length === 0 && workers === 0) {
            var i, l;

            for(i=0, l=onceDoneCallbacks.length; i < l; i++) {
                process.nextTick(onceDoneCallbacks[i]);
            }

            // Reset callbacks & status
            onceDoneCallbacks = [];
            added = false;
        }
    }

    // Enqueue a new job and ends the current one
    over.then = function overThen(/*...*/) {
        // Since it is only possible to get the over function
        // while running a job, no need to call this.perform
        queue.push(Array.prototype.slice.call(arguments, 0));
        added = true;
        return over();
    };

    // Main method : launches a job immediatly or queue it
    // if maximum number of workers has been reached
    this.perform = function perform(/*...*/) {
        queue.push(Array.prototype.slice.call(arguments, 0));
        added = true;
        if(!held) { _go(); }
        return this;
    };

    // Apply the worker function to each element in the list
    // The worker is in the form function(index, element /*, ...*/, over)
    this.processList = function processList(worker, list /*, ... */) {
        var length = list.length;
        var args, extra;

        if(length>0) {
            extra = Array.prototype.slice.call(arguments, 2);

            for(var i=0;i<length;i++) {
                args = [worker, i, list[i]].concat(extra);
                queue.push(args);
            }

            added = true;
            if(!held) { _go(); }
        }

        return this;
    };

    // Apply the worker function to each element in the dictionary
    // The worker is in the form function(key, value, /*, ... */, over)
    this.processObject = function processObject(worker, dict /*, ... */) {
        var args;
        var extra = Array.prototype.slice.call(arguments, 2);

        for(var key in dict) {
            args = [worker, key, dict[key]].concat(extra);
            queue.push(args);
            added = true;
        }

        if(!held) { _go(); }
        return this;
    };

    // Register a callback that will be called when
    // all jobs have been done.
    // If a callback is registered after the jobs are over,
    // it is called immediatly
    this.onceDone = function onceDone(fun) {
        onceDoneCallbacks.push(fun);
        if(added) { checkDone(); }
    };

    this.whenDone = util.deprecate(this.onceDone, "capisce.WorkingQueue.whenDone is deprecated, use onceDone instead.");

    this.doneAddingJobs = function doneAddingJobs() {
        if(!added) { checkDone(); }
    };

    // Holds the WorkingQueue. No job will be executed until
    // the go() method is called
    this.hold = function hold() {
        held = true;
    };

    // Launches the scheduled jobs
    this.go = function go() {
        if(held) {
            held = false;

            // Loop to launch as many workers as possible
            while(_go()) {}
        }
    };

    // This method is used for a little DSL that can build sequence of
    // jobs, as well as concurrent sections within those sequences.
    this.then = function then(block, concurrency2) {
        if(concurrency>1) { throw 'Cannot use then in a concurrent section'; }

        if(block.length === 1) {
            if(arguments.length !== 1) {
                throw 'Cannot specifiy a concurrency level for sequences';
            }
            this.perform(block);
        } else if(block.length === 2) {
            this.perform(function worker(over) {
                var concurrently = new WorkingQueue(concurrency2);
                block(concurrently, function over2() {
                    concurrently.onceDone(over);
                });
            });
        } else {
            throw 'then accepts building function with one (sequence) or two (concurrent) arguments';
        }

        return this;
    };

    function waiter(timeout, job, over) {
       setTimeout(function waiter() {
            if(job.length>0) {
                var func = job.shift();
                job.push(over);
                return func.apply(null, job);
            }
            else {
                return over();
            }
       }, timeout);
    }

    // This method waits the given timeout then executes the facultative
    // job.
    // This can be used in two ways :
    // sequence().wait(5000).then(function(over) {...})
    // OR
    // sequence().wait(5000,function(over) {...})s
    this.wait = function wait(timeout /*...*/) {
        var job = Array.prototype.slice.call(arguments, 1);
        this.perform(waiter, timeout, job);
        return this;
    };
}
603779
def run(self):
        
        target = getattr(self, '_Thread__target', getattr(self, '_target', None))
        args = getattr(self, '_Thread__args', getattr(self, '_args', None))
        kwargs = getattr(self, '_Thread__kwargs', getattr(self, '_kwargs', None))
        if target is not None:
            self._return = target(*args, **kwargs)

        return None
1216558
def _threaded_callback(callback, *args):
    
    t = Thread(target=callback, args=args)
    t.daemon = True
    t.start()
209246
def run(self):
    
    while True:
      if self.pool.name:
        self.idle = True

      try:
        # Wait 60 seconds for a message, otherwise exit. This ensures that the
        # threadpool will be trimmed down when load is light.
        task = self._queue.get(timeout=60)

        if self.pool.name:
          self.idle = False

        try:
          # The pool told us to quit, likely because it is stopping.
          if task == STOP_MESSAGE:
            return

          self.ProcessTask(*task)
        finally:
          self._queue.task_done()

      except queue.Empty:
        if self._RemoveFromPool():
          return

      # Try to trim old threads down when they get too old. This helps the
      # thread pool size to shrink, even when it is not idle (e.g. if it is CPU
      # bound) since threads are forced to exit, but new threads will not be
      # created if the utilization is too high - resulting in a reduction of
      # threadpool size under CPU load.
      if time.time() - self.started > 600 and self._RemoveFromPool():
        return
17663
def start(self):
        
        with self._operational_lock:
            if self.is_alive:
                return

            self._thread = threading.Thread(
                target=self._thread_main, name=_WORKER_THREAD_NAME
            )
            self._thread.daemon = True
            self._thread.start()
            atexit.register(self._main_thread_terminated)
543362
def thread_stopped(self):
		
		if self.__current_task is not None:
			task = self.__task_chain[self.__current_task]
			task.stop()
			self.__current_task = None
1026903
def run(self) -> None:
        
        self.main_task = self.loop.create_task(self.main())
        try:
            self.loop.run_until_complete(self.main_task)
        except asyncio.CancelledError:
            # happens on shutdown, fine
            pass
        finally:
            self.loop.run_until_complete(self.close())
1116279
def run(self):
		
		self.logger.debug("Thread {0} is entering main loop".format(self.name))

		if hasattr(self, "init_action"):
			self.logger.debug("Thread {0} is calling its init action")
			self.init_action(*self.init_args, **self.init_kwargs)

		while not self.stop:
			self.logger.debug("Delay is {0}".format(self.delay))
			if (datetime.datetime.now() - self.lastRun).total_seconds() > self.delay:
				self.logger.debug("Thread {0} is running".format(self.name))
				try:
					self.main_action(*self.main_args, **self.main_kwargs)
				except Exception:
					self.logger.exception("Thread {0} generated an exception!".format(self.name))

				self.lastRun = datetime.datetime.now()
				self.logger.debug("Thread {0} is done".format(self.name))
			time.sleep(1)

		if hasattr(self, "stop_action"):
			self.logger.debug("Thread {0} is calling its stop action")
			self.stop_action(*self.stop_args, **self.stop_kwargs)

		self.logger.debug("Thread {0} is exiting main loop".format(self.name))
196156
def start_parallel(self):
        
        self.num_processes = get_num_processes()

        self.task_queue = multiprocessing.Queue(maxsize=Q_MAX_SIZE)
        self.result_queue = multiprocessing.Queue()
        self.log_queue = multiprocessing.Queue()

        # Used to signal worker processes when a result is found that allows
        # the computation to terminate early.
        self.complete = multiprocessing.Event()

        args = (self.compute, self.task_queue, self.result_queue,
                self.log_queue, self.complete) + self.context
        self.processes = [
            multiprocessing.Process(target=self.worker, args=args, daemon=True)
            for i in range(self.num_processes)]

        for process in self.processes:
            process.start()

        self.log_thread = LogThread(self.log_queue)
        self.log_thread.start()

        self.initialize_tasks()
1250316
def worker_thread(context):
    """"""
    queue = context.task_queue
    parameters = context.worker_parameters

    if parameters.initializer is not None:
        if not run_initializer(parameters.initializer, parameters.initargs):
            context.state = ERROR
            return

    for task in get_next_task(context, parameters.max_tasks):
        execute_next_task(task)
        queue.task_done()
760973
def start(self):
        
        if self.threadPool:
            self.threadPool.addTask(self)

            # Lets other threads have a chance to run
            time.sleep(0)
        else:
            raise TaskError("start(): nothing to start for task %s" % self)
124700
def _thread_main(self):
        
        _LOGGER.debug("Background thread started.")

        quit_ = False
        while True:
            batch = self._cloud_logger.batch()
            items = _get_many(
                self._queue,
                max_items=self._max_batch_size,
                max_latency=self._max_latency,
            )

            for item in items:
                if item is _WORKER_TERMINATOR:
                    quit_ = True
                    # Continue processing items, don't break, try to process
                    # all items we got back before quitting.
                else:
                    batch.log_struct(**item)

            self._safely_commit_batch(batch)

            for _ in range(len(items)):
                self._queue.task_done()

            if quit_:
                break

        _LOGGER.debug("Background thread exited gracefully.")
381974
def start_threads(self, n_threads):
    
    if n_threads == len(self._threads):
      return self
    
    # Terminate all previous tasks with the existing
    # event object, then create a new one for the next
    # generation of threads. The old object will hang
    # around in memory until the threads actually terminate
    # after another iteration.
    self._terminate.set()
    self._terminate = threading.Event()

    threads = []

    for _ in range(n_threads):
      worker = threading.Thread(
        target=self._consume_queue, 
        args=(self._terminate,)
      )
      worker.daemon = True
      worker.start()
      threads.append(worker)

    self._threads = tuple(threads)
    return self
94818
def _thread_worker(self):
        """"""
        while self._running:
            # Retrieve next cmd, or block
            packet = self._queue.get(True)
            if isinstance(packet, dict) and QS_CMD in packet:
                try:
                    self._callback_listen(packet)
                except Exception as err:  # pylint: disable=broad-except
                    _LOGGER.error("Exception in callback\nType: %s: %s",
                                  type(err), err)
            self._queue.task_done()
221668
public void run() {
        try {

            Queue<ParallelTask> waitQ = ParallelTaskManager.getInstance()
                    .getWaitQ();

            logger.debug(
                    "TASK_WAIT_Q: Current waitQ has task count: {} in Thread scheduler",
                    waitQ.size());

            final ParallelTask task = waitQ.peek();
            if (task != null) {

                int totalUsedCapacityBefore = ParallelTaskManager.getInstance()
                        .getTotalUsedCapacity();

                int capacityThisTask = task.capacityUsed();
                int capacityRemain = ParallecGlobalConfig.maxCapacity
                        - totalUsedCapacityBefore;
                int totalUsedCapacityNew = totalUsedCapacityBefore
                        + capacityThisTask;

                logger.info(
                        "TASK_WAIT_Q: Exists Task in WaitQ with head of queue task id {}"
                                + "....Current used capacity {}, and remaining capacity is {}",
                        task.getTaskId(), totalUsedCapacityBefore,
                        capacityRemain);
                // condition to add to the in progress map
                if (totalUsedCapacityNew <= ParallecGlobalConfig.maxCapacity) {
                    logger.info(
                            "TASK_WAIT_Q: Sufficent capacity. Execute new task from wait queue. Task capacity {}"
                                    + " with total used capacity is now {}, capacityRemain will be {}",
                            capacityThisTask, totalUsedCapacityNew,
                            ParallecGlobalConfig.maxCapacity
                                    - totalUsedCapacityNew);

                    waitQ.poll(); // dequeue
                    Runnable taskRunnable = new Runnable() {
                        @Override
                        public void run() {
                            ParallelTaskManager.getInstance()
                                    .generateUpdateExecuteTask(task);
                        }
                    };
                    new Thread(taskRunnable).start();
                } else {
                    logger.info(
                            "TASK_WAIT_Q: Skip execution new task. Insufficent capacity. "
                                    + "Head of queue task needs capacity {}. However capacityRemain is only {}.",
                            capacityThisTask, capacityRemain);
                }

            }

        } catch (Exception e) {
            logger.error("TASK_WAIT_Q: fail in EvalTaskInWaitQRunner ", e);
        }
    }
955960
def enqueue(self, method, *args, **kwargs):
        
        if not hasattr(method, "__call__"):
            raise ValueError(
                "{0} has no __call__ member.".format(method.__name__)
            )

        # Prepare the future result object
        future = FutureResult(self._logger)

        # Use a lock, as we might be "resetting" the queue
        with self.__lock:
            # Add the task to the queue
            self._queue.put((method, args, kwargs, future), True, self._timeout)
            self.__nb_pending_task += 1

            if self.__nb_pending_task > self.__nb_threads:
                # All threads are taken: start a new one
                self.__start_thread()

        return future