Python threading.current_thread() Examples

The following are 30 code examples for showing how to use threading.current_thread(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module threading , or try the search function .

Example 1
Project: zmirror   Author: aploium   File: zmirror.py    License: MIT License 6 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 2
Project: InsightAgent   Author: insightfinder   File: script_runner.py    License: Apache License 2.0 6 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 3
Project: InsightAgent   Author: insightfinder   File: reporting_send.py    License: 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 4
Project: quart   Author: pgjones   File: test_sync.py    License: MIT License 6 votes vote down vote up
def _app() -> Quart:
    app = Quart(__name__)

    @app.route("/", methods=["GET", "POST"])
    def index() -> ResponseReturnValue:
        return request.method

    @app.route("/gen")
    def gen() -> ResponseReturnValue:
        def _gen() -> Generator[bytes, None, None]:
            yield b"%d" % threading.current_thread().ident
            for _ in range(2):
                yield b"b"

        return _gen(), 200

    return app 
Example 5
Project: botbuilder-python   Author: microsoft   File: flask_telemetry_middleware.py    License: 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
Project: jawfish   Author: war-and-code   File: _threading_local.py    License: 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 7
Project: pymumble   Author: Robert904   File: mumble.py    License: 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 8
Project: hsds   Author: HDFGroup   File: get_s3_stats.py    License: 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 9
Project: misp42splunk   Author: remg427   File: engine.py    License: 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 10
Project: misp42splunk   Author: remg427   File: engine.py    License: 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 11
Project: misp42splunk   Author: remg427   File: thread_pool.py    License: 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 12
Project: misp42splunk   Author: remg427   File: engine.py    License: 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 13
Project: misp42splunk   Author: remg427   File: engine.py    License: 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
Project: olympe   Author: Parrot-Developers   File: pomp_loop_thread.py    License: 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 15
Project: olympe   Author: Parrot-Developers   File: pomp_loop_thread.py    License: 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 16
Project: ctw-baseline   Author: yuantailing   File: chineselib.py    License: 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 17
Project: EMANet   Author: XiaLiPKU   File: dataloader.py    License: 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 18
Project: Pyro5   Author: irmen   File: svr_threads.py    License: 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 19
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: verbose.py    License: MIT License 5 votes vote down vote up
def task():
  print("Executing our Task")
  result = 0
  i = 0
  for i in range(10):
    result = result + i
  print("I: {}".format(result))
  print("Task Executed {}".format(threading.current_thread())) 
Example 20
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: threadPool.py    License: MIT License 5 votes vote down vote up
def task():
  print("Executing our Task")
  result = 0
  i = 0
  for i in range(10):
    result = result + i
  print("I: {}".format(result))
  print("Task Executed {}".format(threading.current_thread())) 
Example 21
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: gettingCurrentThread.py    License: MIT License 5 votes vote down vote up
def threadTarget():
  print("Current Thread: {}".format(threading.current_thread())) 
Example 22
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: currentThread.py    License: MIT License 5 votes vote down vote up
def myChildThread():
  print("Child Thread Starting")
  time.sleep(5)
  print("Current Thread ----------")
  print(threading.current_thread())
  print("-------------------------")
  print("Main Thread -------------")
  print(threading.main_thread())
  print("-------------------------")
  print("Child Thread Ending") 
Example 23
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: mainThread.py    License: MIT License 5 votes vote down vote up
def myChildThread():
  print("Child Thread Starting")
  time.sleep(5)
  print("Current Thread ----------")
  print(threading.current_thread())
  print("-------------------------")
  print("Main Thread -------------")
  print(threading.main_thread())
  print("-------------------------")
  print("Child Thread Ending") 
Example 24
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: fullQueue.py    License: MIT License 5 votes vote down vote up
def myPublisher(queue):
  while not queue.full():
    queue.put(1)
    print("{} Appended 1 to queue: {}".format(threading.current_thread(), queue.qsize()))
    time.sleep(1) 
Example 25
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: queueOperations.py    License: MIT License 5 votes vote down vote up
def mySubscriber(queue):
  while True:
    item = queue.get()
    if item is None:
      break
    print("{} removed {} from the queue".format(threading.current_thread(), item))
    print("Queue Size is now: {}".format(queue.qsize()))
    queue.task_done() 
Example 26
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: lifoQueues.py    License: MIT License 5 votes vote down vote up
def mySubscriber(queue):
  while not queue.empty():
    item = queue.get()
    if item is None:
      break
    print("{} removed {} from the queue".format(threading.current_thread(), item))
    queue.task_done() 
Example 27
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: queueJoin.py    License: MIT License 5 votes vote down vote up
def mySubscriber(queue):
  time.sleep(1)
  while not queue.empty():
    item = queue.get()
    if item is None:
      break
    print("{} removed {} from the queue".format(threading.current_thread(), item))
    queue.task_done() 
Example 28
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: webCrawler.py    License: MIT License 5 votes vote down vote up
def __init__(self, baseUrl, linksToCrawl, haveVisited, errorLinks, urlLock):
    threading.Thread.__init__(self);
    print("Web Crawler Worker Started: {}".format(threading.current_thread()))
    self.linksToCrawl = linksToCrawl
    self.haveVisited = haveVisited
    self.baseUrl = baseUrl
    self.urlLock = urlLock
    self.errorLinks = errorLinks 
Example 29
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: threadException.py    License: MIT License 5 votes vote down vote up
def myThread(queue):
  while True:
    try:
      time.sleep(2)
      raise Exception("Exception Thrown In Child Thread {}".format(threading.current_thread()))
    except:
      queue.put(sys.exc_info()) 
Example 30
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: barriers.py    License: MIT License 5 votes vote down vote up
def run(self):
      print("Thread {} working on something".format(threading.current_thread()))
      time.sleep(random.randint(1,10))
      print("Thread {} is joining {} waiting on Barrier".format(threading.current_thread(), self.barrier.n_waiting))
      self.barrier.wait()
      
      print("Barrier has been lifted, continuing with work")