Python threading.current_thread() Examples

The following are 30 code examples of threading.current_thread(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module threading , or try the search function .
Example #1
Source File: script_runner.py    From InsightAgent with Apache License 2.0 7 votes vote down vote up
def acceptThread(parameters):
    acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    acceptor.bind(('', int(parameters['listenPort'])))
    acceptor.listen(5)
    cur_thread = threading.current_thread()
    logger.info("Listening to connections on port " + str(parameters['listenPort']) + '\n')

    while True:
        (clientSock, clientAddr) = acceptor.accept()
        print "==== Output Request ====="
        msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
        logger.info(msg)
        thread3 = threading.Thread(target=sendFile, args=(clientSock, parameters))
        thread3.daemon = True
        thread3.start()
    acceptor.close()
    return 
Example #2
Source File: zmirror.py    From zmirror with MIT License 7 votes vote down vote up
def cron_task_host():
    """定时任务宿主, 每分钟检查一次列表, 运行时间到了的定时任务"""
    while True:
        # 当全局开关关闭时, 自动退出线程
        if not enable_cron_tasks:
            if threading.current_thread() != threading.main_thread():
                exit()
            else:
                return

        sleep(60)
        try:
            task_scheduler.run()
        except:  # coverage: exclude
            errprint('ErrorDuringExecutingCronTasks')
            traceback.print_exc() 
Example #3
Source File: engine.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def run(self):
        """Start job and exit util meet stop condition. """
        _logger.info('Start to process job')

        self._stopped = False
        try:
            self._running_thread = threading.current_thread()
            self._run()
        except Exception:
            _logger.exception('Error encountered while running job.')
            raise
        finally:
            self._terminated.set()
            self._stopped = True

        _logger.info('Job processing finished') 
Example #4
Source File: _threading_local.py    From jawfish with MIT License 6 votes vote down vote up
def create_dict(self):
        """Create a new dict for the current thread, and return it."""
        localdict = {}
        key = self.key
        thread = current_thread()
        idt = id(thread)
        def local_deleted(_, key=key):
            # When the localimpl is deleted, remove the thread attribute.
            thread = wrthread()
            if thread is not None:
                del thread.__dict__[key]
        def thread_deleted(_, idt=idt):
            # When the thread is deleted, remove the local dict.
            # Note that this is suboptimal if the thread object gets
            # caught in a reference loop. We would like to be called
            # as soon as the OS-level thread ends instead.
            local = wrlocal()
            if local is not None:
                dct = local.dicts.pop(idt)
        wrlocal = ref(self, local_deleted)
        wrthread = ref(thread, thread_deleted)
        thread.__dict__[key] = wrlocal
        self.dicts[idt] = wrthread, localdict
        return localdict 
Example #5
Source File: flask_telemetry_middleware.py    From botbuilder-python with MIT License 6 votes vote down vote up
def process_request(self, environ) -> bool:
        """Process the incoming Flask request."""
        # Bot Service doesn't handle anything over 256k
        length = int(environ.get("CONTENT_LENGTH", "0"))
        if length > 256 * 1024:
            print(f"request too long - rejected")
        else:
            body_bytes = environ["wsgi.input"].read(length)
            environ["wsgi.input"] = BytesIO(body_bytes)
            body_unicode = body_bytes.decode("utf-8")

        # Sanity check JSON
        if body_unicode is not None:
            # Integration layer expecting just the json text.
            _REQUEST_BODIES[current_thread().ident] = body_unicode
        return True 
Example #6
Source File: chineselib.py    From ctw-baseline with MIT License 6 votes vote down vote up
def get_feed_dict(self, dest=None):
        tid = threading.current_thread().ident
        self.prefetch.setdefault(tid, {'thread': None, 'data': None})
        current = self.prefetch[tid]

        def assign_thread():
            def assign():
                current['data'] = self.get_feed_dict_sync()
            current['thread'] = threading.Thread(target=assign)
            current['thread'].start()
        if current['thread'] is None:
            assign_thread()
        current['thread'].join()
        res = current['data']
        assign_thread()
        return res 
Example #7
Source File: dataloader.py    From EMANet with GNU General Public License v3.0 6 votes vote down vote up
def _set_SIGCHLD_handler():
    # Windows doesn't support SIGCHLD handler
    if sys.platform == 'win32':
        return
    # can't set signal in child threads
    if not isinstance(threading.current_thread(), threading._MainThread):
        return
    global _SIGCHLD_handler_set
    if _SIGCHLD_handler_set:
        return
    previous_handler = signal.getsignal(signal.SIGCHLD)
    if not callable(previous_handler):
        previous_handler = None

    def handler(signum, frame):
        # This following call uses `waitid` with WNOHANG from C side. Therefore,
        # Python can still get and update the process status successfully.
        _error_if_any_worker_fails()
        if previous_handler is not None:
            previous_handler(signum, frame)

    signal.signal(signal.SIGCHLD, handler)
    _SIGCHLD_handler_set = True 
Example #8
Source File: reporting_send.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def acceptThread():       
    acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        
    acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    acceptor.bind(('', int(uploadPort)))
    acceptor.listen(5)
        
    cur_thread=threading.current_thread()
    while True:            
        (clientSock,clientAddr)=acceptor.accept()
        print "====Output Request:"
        msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
        print msg
        thread3=threading.Thread(target=sendFile(clientSock))
        thread3.daemon=True
        thread3.start()
        #thread3.join()            
    acceptor.close()
    return 
Example #9
Source File: pomp_loop_thread.py    From olympe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_async(self, func, *args, **kwds):
        """
        Fills in a list with the function to be executed in the pomp thread
        and wakes up the pomp thread.
        """
        future = Future(self)
        future._register()

        if threading.current_thread() is not self:
            self.async_pomp_task.append((future, func, args, kwds))
            self._wake_up()
        else:
            try:
                ret = func(*args, **kwds)
            except Exception as e:
                self.logger.exception(
                    "Unhandled exception in async task function"
                )
                future.set_exception(e)
            else:
                if not isinstance(ret, concurrent.futures.Future):
                    future.set_result(ret)
                else:
                    ret.chain(future)
        return future 
Example #10
Source File: mumble.py    From pymumble with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        """Connect to the server and start the loop in its thread.  Retry if requested"""
        self.mumble_thread = threading.current_thread()
        
        # loop if auto-reconnect is requested
        while True:
            self.init_connection()  # reset the connection-specific object members
            
            self.connect()
            
            self.loop()
        
            if not self.reconnect or not self.parent_thread.is_alive():
                break
            
            time.sleep(PYMUMBLE_CONNECTION_RETRY_INTERVAL) 
Example #11
Source File: pomp_loop_thread.py    From olympe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def then(self, fn, deferred=False):
        result = Future(self._loop)
        result._register()

        def callback(_):
            try:
                if deferred:
                    temp = self._loop.run_later(fn, self.result())
                    temp.chain(result)
                elif not threading.current_thread() is self._loop:
                    temp = self._loop.run_async(fn, self.result())
                    temp.chain(result)
                else:
                    result.set_result(fn(self.result()))
            except Exception as e:
                self.logger.exception(
                    "Unhandled exception while chaining futures"
                )
                result.set_exception(e)
            except:
                result.cancel()

        self.add_done_callback(callback)
        return result 
Example #12
Source File: get_s3_stats.py    From hsds with Apache License 2.0 6 votes vote down vote up
def get_sizes(jsn):
   thrd = threading.current_thread()
   logging.info('starting thread '+str(thrd.ident)+' ...')
   try:
      while True:
         if queue.empty() == True: 
            break
         itm = queue.get()
         logging.info(str(thrd.ident)+' :' +str(itm))
         val = get_remote_size(itm)
         if val != None: jsn[itm]['objsize'] = val
         queue.task_done()
   except Queue.Empty: 
      pass
   logging.info('thread '+str(thrd.ident)+' done...') 
#get_sizes

#--------------------------------------------------------------------------------- 
Example #13
Source File: engine.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def run(self):
        """Start job and exit util meet stop condition. """
        _logger.info('Start to process job')

        self._stopped = False
        try:
            self._running_thread = threading.current_thread()
            self._run()
        except Exception:
            _logger.exception('Error encountered while running job.')
            raise
        finally:
            self._terminated.set()
            self._stopped = True

        _logger.info('Job processing finished') 
Example #14
Source File: engine.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def terminate(self, block=True, timeout=30):
        """Terminate this job, the current thread will blocked util
        the job is terminate finished if block is True """
        if self.is_stopped():
            _logger.info('Job already been stopped.')
            return

        if self._running_thread == threading.current_thread():
            _logger.warning('Job cannot terminate itself.')
            return

        _logger.info('Stopping job')
        self._should_stop = True

        if not block:
            return
        if not self._terminated.wait(timeout):
            _logger.warning('Terminating job timeout.') 
Example #15
Source File: thread_pool.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _do_admin(self):
        admin_q = self._admin_queue
        resize_win = self._resize_window
        while 1:
            try:
                wakup = admin_q.get(timeout=resize_win + 1)
            except queue.Empty:
                self._do_resize_according_to_loads()
                continue

            if wakup is None:
                break
            else:
                self._do_resize_according_to_loads()
        log.logger.info("ThreadPool admin thread=%s stopped.",
                        threading.current_thread().getName()) 
Example #16
Source File: engine.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def terminate(self, block=True, timeout=30):
        """Terminate this job, the current thread will blocked util
        the job is terminate finished if block is True """
        if self.is_stopped():
            _logger.info('Job already been stopped.')
            return

        if self._running_thread == threading.current_thread():
            _logger.warning('Job cannot terminate itself.')
            return

        _logger.info('Stopping job')
        self._should_stop = True

        if not block:
            return
        if not self._terminated.wait(timeout):
            _logger.warning('Terminating job timeout.') 
Example #17
Source File: svr_threads.py    From Pyro5 with MIT License 6 votes vote down vote up
def close(self):
        if not self.closed:
            log.debug("closing down")
            for w in list(self.busy):
                w.process(None)
            for w in list(self.idle):
                w.process(None)
            self.closed = True
            time.sleep(0.1)
            idle, self.idle = self.idle, set()
            busy, self.busy = self.busy, set()
            # check if the threads that are joined are not the current thread.
            current_thread = threading.current_thread()
            while idle:
                p = idle.pop()
                if p is not current_thread:
                    p.join(timeout=0.1)
            while busy:
                p = busy.pop()
                if p is not current_thread:
                    p.join(timeout=0.1) 
Example #18
Source File: client.py    From Pyro5 with MIT License 5 votes vote down vote up
def func(uri):
    # This will run in a thread. Create a proxy just for this thread:
    with Proxy(uri) as p:
        processed = p.delay()
        print("[ thread %s called delay, processed by: %s ]  " % (threading.current_thread().getName(), processed)) 
Example #19
Source File: request_state.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def end_request(self):
    """Ends the request and blocks until all threads for this request finish."""
    thread_id = threading.current_thread().ident
    with self._condition:
      self._threads.remove(thread_id)
      while self._threads:
        self._condition.wait() 
Example #20
Source File: server.py    From Pyro5 with MIT License 5 votes vote down vote up
def echo(self, message):
        ctx = Pyro5.api.current_context
        print("\nGot Message:", message)
        print("  thread: ", threading.current_thread().ident)
        print("  obj.pyroid: ", self._pyroId)
        print("  obj.daemon: ", self._pyroDaemon)
        print("  context.client: ", ctx.client)
        print("  context.client_sock_addr: ", ctx.client_sock_addr)
        print("  context.seq: ", ctx.seq)
        print("  context.msg_flags: ", ctx.msg_flags)
        print("  context.serializer_id: ", ctx.serializer_id)
        print("  context.correlation_id:", ctx.correlation_id)
        if "XYZZ" in ctx.annotations:
            print("  custom annotation 'XYZZ':", bytes(ctx.annotations["XYZZ"]))
        return message 
Example #21
Source File: server.py    From Pyro5 with MIT License 5 votes vote down vote up
def onewaydelay(self):
        threadname = threading.current_thread().getName()
        print("onewaydelay called in thread %s" % threadname)
        time.sleep(1)
        self.callcount += 1


# main program 
Example #22
Source File: __init__.py    From recruit with Apache License 2.0 5 votes vote down vote up
def __init__(self, path, threaded=True, timeout=None):
        """
        >>> lock = LockBase('somefile')
        >>> lock = LockBase('somefile', threaded=False)
        """
        super(LockBase, self).__init__(path)
        self.lock_file = os.path.abspath(path) + ".lock"
        self.hostname = socket.gethostname()
        self.pid = os.getpid()
        if threaded:
            t = threading.current_thread()
            # Thread objects in Python 2.4 and earlier do not have ident
            # attrs.  Worm around that.
            ident = getattr(t, "ident", hash(t))
            self.tname = "-%x" % (ident & 0xffffffff)
        else:
            self.tname = ""
        dirname = os.path.dirname(self.lock_file)

        # unique name is mostly about the current process, but must
        # also contain the path -- otherwise, two adjacent locked
        # files conflict (one file gets locked, creating lock-file and
        # unique file, the other one gets locked, creating lock-file
        # and overwriting the already existing lock-file, then one
        # gets unlocked, deleting both lock-file and unique file,
        # finally the last lock errors out upon releasing.
        self.unique_name = os.path.join(dirname,
                                        "%s%s.%s%s" % (self.hostname,
                                                       self.tname,
                                                       self.pid,
                                                       hash(self.path)))
        self.timeout = timeout 
Example #23
Source File: client.py    From Pyro5 with MIT License 5 votes vote down vote up
def other_thread_call():
    try:
        proxy.ping()
        print("You should not see this!! the call succeeded in thread", threading.current_thread())
    except Pyro5.errors.PyroError as x:
        print("Expected exception in thread", threading.current_thread())
        print("Exception was: ", x) 
Example #24
Source File: connection_observer.py    From moler with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def inside_main_thread():
        in_main_thread = threading.current_thread() is threading.main_thread()
        return in_main_thread 
Example #25
Source File: connection_observer.py    From moler with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def inside_main_thread():
        in_main_thread = isinstance(threading.current_thread(), threading._MainThread)
        return in_main_thread 
Example #26
Source File: asyncio_runner.py    From moler with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_system_resources_limit(connection_observer, observer_lock, logger):
    # The number of file descriptors currently opened by this process
    curr_fds_open, curr_threads_nb = system_resources_usage()

    if curr_fds_open > max_open_files_limit_soft - 10:
        err_cause = "Can't run new asyncio loop - ALMOST REACHED MAX OPEN FILES LIMIT"
        msg = "{} ({}). Now {} FDs open, {} threads active.".format(err_cause, max_open_files_limit_soft,
                                                                    curr_fds_open, curr_threads_nb)
        logger.warning(msg)
        limit_exception = MolerException(msg)
        # make future done and observer done-with-exception
        with observer_lock:
            connection_observer.set_exception(limit_exception)
        # We need to return future informing "it's impossible to create new event loop"
        # However, it can't be asyncio.Future() since it requires event loop ;-)
        # We would get something like:
        #
        #    impossible_future = asyncio.Future()
        #  File "/opt/ute/python3/lib/python3.6/asyncio/events.py", line 676, in get_event_loop
        #    return get_event_loop_policy().get_event_loop()
        #  File "/opt/ute/python3/lib/python3.6/asyncio/events.py", line 584, in get_event_loop
        #    % threading.current_thread().name)
        # RuntimeError: There is no current event loop in thread 'Thread-5090'.
        #
        # So, we use concurrent.futures.Future - it has almost same API (duck typing for runner.wait_for() below)
        impossible_future = concurrent.futures.Future()
        impossible_future.set_result(None)
        return impossible_future
    return None 
Example #27
Source File: stdlib.py    From tox with MIT License 5 votes vote down vote up
def is_main_thread():
    """returns true if we are within the main thread"""
    cur_thread = threading.current_thread()
    if sys.version_info >= (3, 4):
        return cur_thread is threading.main_thread()
    else:
        # noinspection PyUnresolvedReferences
        return isinstance(cur_thread, threading._MainThread)


# noinspection PyPep8Naming 
Example #28
Source File: worker.py    From stream with MIT License 5 votes vote down vote up
def handle(self):
    data = str(self.request.recv(1024), 'ascii')
    cur_thread = threading.current_thread()
    response = bytes("{}: {}".format(cur_thread.name, data), 'ascii')
    self.request.sendall(response) 
Example #29
Source File: pomp_loop_thread.py    From olympe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def stop(self):
        """
        Stop thread to manage commands send to the drone
        """
        if not self.running:
            return False
        self.running = False
        if threading.current_thread().ident != self.ident:
            self._wake_up()
            self.join()
        return True 
Example #30
Source File: crashsignal.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def _handle_early_exits(self, exc):
        """Handle some special cases for the exception hook.

        Return value:
            True: Exception hook should be aborted.
            False: Continue handling exception.
        """
        exctype, _excvalue, tb = exc

        if not self._quitter.quit_status['crash']:
            log.misc.error("ARGH, there was an exception while the crash "
                           "dialog is already shown:", exc_info=exc)
            return True

        log.misc.error("Uncaught exception", exc_info=exc)

        is_ignored_exception = (exctype is bdb.BdbQuit or
                                not issubclass(exctype, Exception))

        if 'pdb-postmortem' in objects.debug_flags:
            if tb is None:
                pdb.set_trace()  # noqa: T100
            else:
                pdb.post_mortem(tb)

        if is_ignored_exception or 'pdb-postmortem' in objects.debug_flags:
            # pdb exit, KeyboardInterrupt, ...
            sys.exit(usertypes.Exit.exception)

        if threading.current_thread() != threading.main_thread():
            log.misc.error("Ignoring exception outside of main thread... "
                           "Please report this as a bug.")
            return True

        return False