the heart of the threading code
7714
def add_message message
    el = @messages[message.id]
    return if el.message # we've seen it before

    #puts "adding: #{message.id}, refs #{message.refs.inspect}"

    el.message = message
    oldroot = el.root

    ## link via references:
    (message.refs + [el.id]).inject(nil) do |prev, ref_id|
      ref = @messages[ref_id]
      link prev, ref if prev
      ref
    end

    ## link via in-reply-to:
    message.replytos.each do |ref_id|
      ref = @messages[ref_id]
      link ref, el, true
      break # only do the first one
    end

    root = el.root
    key =
      if thread_by_subj?
        Message.normalize_subj root.subj
      else
        root.id
      end

    ## check to see if the subject is still the same (in the case
    ## that we first added a child message with a different
    ## subject)
    if root.thread
      if @threads.member?(key) && @threads[key] != root.thread
        @threads.delete key
      end
    else
      thread = @threads[key]
      thread << root
      root.thread = thread
    end

    ## last bit
    @num_messages += 1
  end
404309
def threads_init(gtk=True):
    
    # enable X11 multithreading
    x11.XInitThreads()
    if gtk:
        from gtk.gdk import threads_init
        threads_init()
481435
private static <T> ThreadContext<T> getCurrentThreadContext(ThreadContext<T> threadContext)
    {
        return ((ThreadContextImpl<T>) threadContext).get();
    }
181884
def _getThread(self, given_thread_id=None, given_thread_type=None):
        
        if given_thread_id is None:
            if self._default_thread_id is not None:
                return self._default_thread_id, self._default_thread_type
            else:
                raise ValueError("Thread ID is not set")
        else:
            return given_thread_id, given_thread_type
395653
public int getRunningThreadCount() {
        int rc = 0;
        WorkQueue[] ws; WorkQueue w;
        if ((ws = workQueues) != null) {
            for (int i = 1; i < ws.length; i += 2) {
                if ((w = ws[i]) != null && w.isApparentlyUnblocked())
                    ++rc;
            }
        }
        return rc;
    }
61239
def threadid(self):
        
        current = self.thread.ident
        main = get_main_thread()
        if main is None:
            return current
        else:
            return current if current != main.ident else None
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)
19607
def threadpooled(
    func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]],
    *,
    loop_getter: typing.Union[typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop],
    loop_getter_need_context: bool = False,
) -> typing.Callable[..., "asyncio.Task[typing.Any]"]:
    """"""
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)
373841
def get_f_code_idx():
    
    frame = sys._getframe()
    frame_ptr = id(frame)

    LARGE_ENOUGH = 20

    # Look through the frame object until we find the f_tstate variable, whose
    # value we know from above.
    ptrs = [ctypes.c_voidp.from_address(frame_ptr+i*svp)
            for i in range(LARGE_ENOUGH)]

    # Find its index into the structure
    ptrs = [p.value for p in ptrs]

    fcode_ptr = id(frame.f_code)
    try:
        threadstate_idx = ptrs.index(fcode_ptr)
    except ValueError:
        log.critical("rootpy bug! Please report this.")
        raise
    return threadstate_idx
1193669
def _threaded_start(self):
        '''
        
        '''
        self.active = True
        self.thread = Thread(target=self._main_loop)
        self.thread.setDaemon(True)
        self.thread.start()
957606
def get_threads(self):
        
        thread_list = {}
        for thread in threading.enumerate():
            thread_ident = thread.ident
            thread_list[thread_ident] = {
                "ident": thread_ident,
                "name": thread.name,
                "is_debugger": thread_ident == self.debugger_thread_ident,
                "is_debugged": thread_ident == self.debugged_thread_ident
            }
        return thread_list
189675
public synchronized boolean getThreadCpuTimes(int pid, long[] result) {
        int rc = GetThreadTimes(pid, callBuf);
        if (rc == 0) {
            long ktime = (0xFFFFFFFFl & callBuf[4]) | ((long)callBuf[5]) << 32;
            long utime = (0xFFFFFFFFl & callBuf[6]) | ((long)callBuf[7]) << 32;
            
            result[0] = ktime / 10;
            result[1] = utime / 10;
            return true;
        }
        else {
            System.out.println("Error code: " + rc);
            return false;
        }
    }
1148394
private static HystrixThreadPoolKey initThreadPoolKey(HystrixThreadPoolKey threadPoolKey, HystrixCommandGroupKey groupKey, String threadPoolKeyOverride) {
        if (threadPoolKeyOverride == null) {
            // we don't have a property overriding the value so use either HystrixThreadPoolKey or HystrixCommandGroup
            if (threadPoolKey == null) {
                /* use HystrixCommandGroup if HystrixThreadPoolKey is null */
                return HystrixThreadPoolKey.Factory.asKey(groupKey.name());
            } else {
                return threadPoolKey;
            }
        } else {
            // we have a property defining the thread-pool so use it instead
            return HystrixThreadPoolKey.Factory.asKey(threadPoolKeyOverride);
        }
    }
503735
def threadsafe_generator(generator_func):
    
    def decoration(*args, **keyword_args):
        """A thread-safe decoration for a generator function."""
        return ThreadSafeIter(generator_func(*args, **keyword_args))
    return decoration
66745
def do(self, arg):
    ""
    thread = self.get_thread_from_prefix()
    print "Exception handlers for thread %d" % thread.get_tid()
    print
    table = Table()
    table.addRow("Block", "Function")
    bits = thread.get_bits()
    for (seh, seh_func) in thread.get_seh_chain():
        if seh is not None:
            seh      = HexDump.address(seh, bits)
        if seh_func is not None:
            seh_func = HexDump.address(seh_func, bits)
        table.addRow(seh, seh_func)
    print table.getOutput()
11614
def get_box_threads(self, box_key):
		'''
		'''
		uri = '/'.join([
						self.api_uri,
						self.boxes_suffix,
						box_key,
						self.threads_suffix
						])
		return self._req('get', uri)