取出ThreadLocal的上下文信息.
543825
@SuppressWarnings("unchecked")
	public static <T> T get(String key) {
		return (T) (contextMap.get().get(key));
	}
357229
def managing_thread_main_simple():
	
	import shutit_global
	last_msg = ''
	while True:
		printed_anything = False
		if shutit_global.shutit_global_object.log_trace_when_idle and time.time() - shutit_global.shutit_global_object.last_log_time > 10:
			this_msg = ''
			this_header = ''
			for thread_id, stack in sys._current_frames().items():
				# ignore own thread:
				if thread_id == threading.current_thread().ident:
					continue
				printed_thread_started = False
				for filename, lineno, name, line in traceback.extract_stack(stack):
					if not printed_anything:
						printed_anything = True
						this_header += '\n='*80 + '\n'
						this_header += 'STACK TRACES PRINTED ON IDLE: THREAD_ID: ' + str(thread_id) + ' at ' + time.strftime('%c') + '\n'
						this_header += '='*80 + '\n'
					if not printed_thread_started:
						printed_thread_started = True
					this_msg += '%s:%d:%s' % (filename, lineno, name) + '\n'
					if line:
						this_msg += '  %s' % (line,) + '\n'
			if printed_anything:
				this_msg += '='*80 + '\n'
				this_msg += 'STACK TRACES DONE\n'
				this_msg += '='*80 + '\n'
			if this_msg != last_msg:
				print(this_header + this_msg)
				last_msg = this_msg
		time.sleep(5)
158488
def threadsafe_call(self, fn, *args, **kwargs):
        """"""
        def handler():
            try:
                fn(*args, **kwargs)
            except Exception:
                warn("error caught while excecuting async callback\n%s\n",
                     format_exc())

        def greenlet_wrapper():
            gr = greenlet.greenlet(handler)
            gr.switch()

        self._async_session.threadsafe_call(greenlet_wrapper)
646288
public void purgeThreadLocal() {
        // if thread local pools exist, check to see if we have one created and
        // therefore need to tell it to purge
        if (null != threadLocals) {
            LocalThreadObjectPool pool = threadLocals.get();
            if (null != pool) {
                Object[] data = pool.purge();
                if (0 < data.length) {
                    mainPool.putBatch(data);
                }
            }
        }
    }
693081
def _get_active_threads_names():
        """"""
        active_threads = threading.enumerate()
        return FormattedText().join(
            [
                FormattedText().newline().normal(" - {name}").start_format().bold(name=thread.name).end_format()
                for thread in active_threads
            ]
        )
995198
def get_selected_thread(self):
        """"""
        threadlinewidget = self.get_selected_threadline()
        thread = None
        if threadlinewidget:
            thread = threadlinewidget.get_thread()
        return thread
523804
def _thread_worker_fn(samples, batchify_fn, dataset):
    """"""
    if isinstance(samples[0], (list, tuple)):
        batch = [batchify_fn([dataset[i] for i in shard]) for shard in samples]
    else:
        batch = batchify_fn([dataset[i] for i in samples])
    return batch
399180
private ThreadLocal<StringMap> createThreadLocalMap() {
        final PropertiesUtil managerProps = PropertiesUtil.getProperties();
        final boolean inheritable = managerProps.getBooleanProperty(INHERITABLE_MAP);
        if (inheritable) {
            return new InheritableThreadLocal<StringMap>() {
                @Override
                protected StringMap childValue(final StringMap parentValue) {
                    return parentValue != null ? createStringMap(parentValue) : null;
                }
            };
        }
        // if not inheritable, return plain ThreadLocal with null as initial value
        return new ThreadLocal<>();
    }
949033
def dump_threads(stream=None):
    '''
    
    '''
    if stream is None:
        stream = sys.stderr
    thread_id_to_name = {}
    try:
        for t in threading.enumerate():
            thread_id_to_name[t.ident] = '%s  (daemon: %s, pydevd thread: %s)' % (
                t.name, t.daemon, getattr(t, 'is_pydev_daemon_thread', False))
    except:
        pass

    from _pydevd_bundle.pydevd_additional_thread_info_regular import _current_frames

    stream.write('===============================================================================\n')
    stream.write('Threads running\n')
    stream.write('================================= Thread Dump =================================\n')
    stream.flush()

    for thread_id, stack in _current_frames().items():
        stream.write('\n-------------------------------------------------------------------------------\n')
        stream.write(" Thread %s" % thread_id_to_name.get(thread_id, thread_id))
        stream.write('\n\n')

        for i, (filename, lineno, name, line) in enumerate(traceback.extract_stack(stack)):

            stream.write(' File "%s", line %d, in %s\n' % (filename, lineno, name))
            if line:
                stream.write("   %s\n" % (line.strip()))

            if i == 0 and 'self' in stack.f_locals:
                stream.write('   self: ')
                try:
                    stream.write(str(stack.f_locals['self']))
                except:
                    stream.write('Unable to get str of: %s' % (type(stack.f_locals['self']),))
                stream.write('\n')
        stream.flush()

    stream.write('\n=============================== END Thread Dump ===============================')
    stream.flush()
996218
def thread(self):
        """"""
        if not self._thread_calculated:
            self._thread_calculated = True

            split_tokens = self.split_tokens

            if not self.datetime_nextpos:
                return None
            if len(split_tokens) <= self.datetime_nextpos:
                return None

            connection_token = split_tokens[self.datetime_nextpos]
            match = re.match(r'^\[([^\]]*)\]$', connection_token)
            if match:
                self._thread = match.group(1)

            if self._thread is not None:
                if self._thread in ['initandlisten', 'mongosMain']:
                    if len(split_tokens) >= 5 and split_tokens[-5][0] == '#':
                        self._conn = 'conn' + split_tokens[-5][1:]
                elif self._thread.startswith('conn'):
                    self._conn = self._thread
        return self._thread
56878
public static void cleanupThreadLocals(Thread thread)
   {
      if (!OperatingSystemUtils.isJava8())
      {
         return;
      }
      try
      {
         if (thread != null)
         {
            cleanField(thread, Thread.class.getDeclaredField("threadLocals"));
            cleanField(thread, Thread.class.getDeclaredField("inheritableThreadLocals"));
         }
      }
      catch (Exception e)
      {
         log.log(Level.WARNING, "Failed to cleanup ThreadLocal instances for Thread [" + thread + "]", e);
      }
   }
148176
public static AccessContext getAccessContextOnThread() {
        final Stack<AccessContext> stack = threadLocal.get();
        return stack != null ? stack.peek() : null;
    }
1309796
private static Thread findActiveThreadByName(ThreadGroup group, String threadName) 
    {
        Thread result = null;
        
        // Get threads in 'group'
        int numThreads = group.activeCount();
        Thread[] threads = new Thread[numThreads * 2];
        numThreads = group.enumerate(threads, false);

        // Enumerate each thread in 'group'
        for (int i = 0; i < numThreads; i++) {
            if (threads[i].getName().equals(threadName)) {
                return threads[i];
            }
        }

        // Get thread subgroups of 'group'
        int numGroups = group.activeGroupCount();
        ThreadGroup[] groups = new ThreadGroup[numGroups * 2];
        numGroups = group.enumerate(groups, false);

        // Recursively visit each subgroup
        for (int i = 0; i < numGroups; i++) {
            result = findActiveThreadByName(groups[i], threadName);
            
            if (result != null) {
                break;
            }
        }
        
        return result;
    }
783956
def thread_info(self):
        """"""
        tid = threading.current_thread().name
        if tid == 'MainThread':
            tid = 'Main'
        current = fibers.current()
        fid = getattr(current, 'name') if current.parent else 'Root'
        return '{}/{}'.format(tid, fid)
494496
def _trace_line (frame, event, arg):
    """"""
    name = frame.f_globals["__name__"]
    if name in _trace_ignore:
        return _trace_line
    for pat in _trace_filter:
        if not pat.match(name):
            return _trace_line
    lineno = frame.f_lineno
    filename = frame.f_globals["__file__"]
    if filename.endswith((".pyc", ".pyo")):
        filename = filename[:-1]
    line = linecache.getline(filename, lineno)
    currentThread = threading.currentThread()
    tid = currentThread.ident
    tname = currentThread.getName()
    args = (tid, tname, time.time(), line.rstrip(), name, lineno)
    print("THREAD(%d) %r %.2f %s # %s:%d" % args)
122635
def task(name=None, t=INFO, *args, **kwargs):
    

    def c_run(name, f, t, args, kwargs):
        def run(*largs, **lkwargs):
            thread = __get_current_thread()
            old_name = __THREAD_PARAMS[thread][__THREAD_PARAMS_FNAME_KEY]
            __THREAD_PARAMS[thread][__THREAD_PARAMS_FNAME_KEY] = name

            r = log(name, f, t, largs, lkwargs, *args, **kwargs)

            __THREAD_PARAMS[thread][__THREAD_PARAMS_FNAME_KEY] = old_name
            return r

        return run

    if callable(name):
        f = name
        name = f.__name__

        return c_run(name, f, t, args, kwargs)

    if name == None:
        def wrapped(f):
            name = f.__name__
            return c_run(name, f, t, args, kwargs)

        return wrapped
    else:
        return lambda f: c_run(name, f, t, args, kwargs)
192662
def patch_thread(threading=True, _threading_local=True, Queue=True, Event=False):
    
    monkey.patch_module('thread')
    if threading:
        monkey.patch_module('threading')
        threading = __import__('threading')
        if Event:
            from gevent.event import Event
            threading.Event = Event
        if Queue:
            from gevent import queue
            threading.queue = queue
    if _threading_local:
        _threading_local = __import__('_threading_local')
        from gevent.local import local
        _threading_local.local = local