Execute the worker thread.

        Returns:
            `None`
969591
def run(self, **kwargs):
        
        super().run(**kwargs)
        scheduler = self.scheduler_plugins[self.active_scheduler]()

        if not kwargs['no_daemon']:
            self.log.info('Starting {} worker with {} threads checking for new messages every {} seconds'.format(
                scheduler.name,
                kwargs['threads'],
                kwargs['delay']
            ))

            for i in range(kwargs['threads']):
                thd = threading.Thread(
                    target=self.execute_worker_thread,
                    args=(scheduler.execute_worker, kwargs['delay'])
                )
                thd.start()
        else:
            self.log.info('Starting {} worker for a single non-daemon execution'.format(
                scheduler.name
            ))
            scheduler.execute_worker()
74704
def spawn_thread(self):
        ''
        self.thread = threading.Thread(target=self.run, args=(False,))
        self.thread.daemon = True
        self.thread.start()
96943
def transaction():
    
    client = default_client()
    _thread.client = client.pipeline()
    try:
        yield
        _thread.client.execute()
    finally:
        _thread.client = client
702228
def run(self, target, callback = None, name = None, complete = None, *args, **kargs):
        
        self.count_lock.acquire()
        if not self.workers:
            self.count_lock.release()
            self.add(name = name)
        else:
            self.count_lock.release()
        self.tasks.put((target, callback, name, complete, args, kargs))
1113281
def _loop_thread_main(self):
        """"""

        asyncio.set_event_loop(self.loop)
        self._loop_check.inside_loop = True

        try:
            self._logger.debug("Starting loop in background thread")
            self.loop.run_forever()
            self._logger.debug("Finished loop in background thread")
        except:  # pylint:disable=bare-except;This is a background worker thread.
            self._logger.exception("Exception raised from event loop thread")
        finally:
            self.loop.close()
308736
def _execute_callback(self, callback, data):
        """"""
        web_client = WebClient(
            token=self.token, base_url=self.base_url, ssl=self.ssl, proxy=self.proxy
        )
        with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
            # Execute the callback on a separate thread,
            future = executor.submit(
                callback, rtm_client=self, web_client=web_client, data=data
            )

            while future.running():
                pass

            future.result()
45441
def cmd(send, *_):
    
    thread_names = []
    for x in sorted(threading.enumerate(), key=lambda k: k.name):
        res = re.match(r'Thread-(\d+$)', x.name)
        if res:
            tid = int(res.group(1))
            # Handle the main server thread (permanently listed as _worker)
            if x._target.__name__ == '_worker':
                thread_names.append((tid, "%s running server thread" % x.name))
            # Handle the multiprocessing pool worker threads (they don't have names beyond Thread-x)
            elif x._target.__module__ == 'multiprocessing.pool':
                thread_names.append((tid, "%s running multiprocessing pool worker thread" % x.name))
        # Handle everything else including MainThread and deferred threads
        else:
            res = re.match(r'Thread-(\d+)', x.name)
            tid = 0
            if res:
                tid = int(res.group(1))
            thread_names.append((tid, x.name))
    for x in sorted(thread_names, key=lambda k: k[0]):
        send(x[1])
1206764
def _start_worker(self, worker: Worker):
        
        # This function is called from main thread and from worker pools threads to start their children threads
        with self.running_workers_lock:
            self.running_workers.append(worker)
        thread = SchedulerThread(worker, self._worker_ended)
        thread.start()
        # This may or may not be posted to a background thread (see set_callbacks)
        self.worker_start_callback(worker)
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()
69190
def fire(self, *args, **kw):
        
        result = []

        with self._hlock:
            handlers = self.handlers

        if self.threads == 0:  # same-thread execution - synchronized
            for k in handlers:
                # handler, memoize, timeout
                h, m, t = handlers[k]
                try:
                    r = self._memoize(h, m, t, *args, **kw)
                    result.append(tuple(r))
                except:
                    result.append((False, self._error(sys.exc_info()), h))

        elif self.threads > 0:  # multi-thread execution - desynchronized if self.threads > 1
            queue = Queue()

            # result lock just in case [].append() is not  
            # thread-safe in other Python implementations
            rlock = RLock()

            def _execute(*args, **kw):
                """ Executes all handlers stored in the queue """
                while True:
                    try:
                        item = queue.get()
                        if item is None:
                            queue.task_done()
                            break

                        # handler, memoize, timeout
                        h, m, t = handlers[item]  # call under active lock

                        try:
                            r = self._memoize(h, m, t, *args, **kw)
                            if not self.asynch:
                                with rlock:
                                    result.append(tuple(r))
                        except:
                            if not self.asynch:
                                with rlock:
                                    result.append((False, self._error(sys.exc_info()), h))

                        queue.task_done()

                    except Empty:  # never triggered, just to be safe
                        break

            if handlers:
                threads = self._threads(handlers=handlers)

                for _ in range(threads):
                    t = Thread(target=_execute, args=args, kwargs=kw)
                    t.daemon = True
                    t.start()

                for k in handlers:
                    queue.put(k)

                    if self.asynch:  # main thread, no locking required
                        h, _, _ = handlers[k]
                        result.append((None, None, h))

                for _ in range(threads):
                    queue.put(None)  # stop each worker

                if not self.asynch:
                    queue.join()

        return tuple(result) or None
268819
def step(self):
        
        message = self.get_message()
        if message is None:

            self.sleep(self.idle_time)
            return None

        self.dispatch(message)
        # In non-greenthread environments this does nothing. In green-thread
        # environments this yields the context so messages can be acted upon
        # before exhausting the threadpool.
        self.sleep(0)
1370760
def start_worker_thread(
            self,
            sleep_interval=1.0):
        
        # Start a worker thread responsible for sending logs
        if self.sleep_interval > 0:
            self.debug_log(
                'starting worker thread')
            self.timer = Timer(
                sleep_interval,
                self.perform_work)
            self.timer.daemon = True  # Auto-kill thread if main process exits
            self.timer.start()
1152322
def run(self, input_fname, ids_per_job, stagger=0, **wait_params):
        
        submit_thread = Thread(target=self.submit_reading,
                               args=(input_fname, 0, None, ids_per_job),
                               kwargs={'stagger': stagger},
                               daemon=True)
        submit_thread.start()
        self.watch_and_wait(**wait_params)
        submit_thread.join(0)
        if submit_thread.is_alive():
            logger.warning("Submit thread is still running even after job"
                           "completion.")
        return
549554
def _thread_main(self):
        
        quit_ = False

        while True:
            items = self._get_items()
            data = []

            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:
                    data.extend(item)

            if data:
                try:
                    self.exporter.emit(data)
                except Exception:
                    logging.exception(
                        '%s failed to emit data.'
                        'Dropping %s objects from queue.',
                        self.exporter.__class__.__name__,
                        len(data))
                    pass

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

            # self._event is set at exit, at which point we start draining the
            # queue immediately. If self._event is unset, block for
            # self.wait_period between each batch of exports.
            self._event.wait(self._wait_period)

            if quit_:
                break
447349
def start(self):
        
        self.thread_handler.run(target=self.start_blocking)
        self.thread_handler.start_run_loop()
330807
def start(self):
        
        with self._operational_lock:
            if self._thread is not None:
                raise ValueError("Dispatcher is already running.")

            flow_control = self._manager.flow_control
            worker = helper_threads.QueueCallbackWorker(
                self._queue,
                self.dispatch_callback,
                max_items=flow_control.max_request_batch_size,
                max_latency=flow_control.max_request_batch_latency,
            )
            # Create and start the helper thread.
            thread = threading.Thread(name=_CALLBACK_WORKER_NAME, target=worker)
            thread.daemon = True
            thread.start()
            _LOGGER.debug("Started helper thread %s", thread.name)
            self._thread = thread
1282564
def execute(self):
        
        stack = self._stack
        callbacks = self._callbacks
        self._stack = []
        self._callbacks = []

        deferred = []

        build = self._nested_future

        pipe = self._pipeline(self.connection_name)
        for item, args, kwargs, ref in stack:
            f = getattr(pipe, item)
            deferred.append(build(f(*args, **kwargs), ref))

        inject_callbacks = getattr(self.parent, '_inject_callbacks')
        inject_callbacks(deferred + callbacks)