Skip site navigation (1)Skip section navigation (2)
Date:      Tue, 15 Jan 2013 15:54:03 -0500
From:      Trent Nelson <trent@snakebite.org>
To:        <freebsd-hackers@freebsd.org>
Subject:   Getting the current thread ID without a syscall?
Message-ID:  <20130115205403.GA52904@snakebite.org>

next in thread | raw e-mail | index | archive | help
Howdy,

    I have an unusual requirement: I need to get the current thread ID
    in as few instructions as possible.  On Windows, I managed to come
    up with this glorious hack:

#ifdef WITH_INTRINSICS
#   ifdef MS_WINDOWS
#       include <intrin.h>
#       if defined(MS_WIN64)
#           pragma intrinsic(__readgsdword)
#           define _Py_get_current_process_id() (__readgsdword(0x40))
#           define _Py_get_current_thread_id()  (__readgsdword(0x48))
#       elif defined(MS_WIN32)
#           pragma intrinsic(__readfsdword)
#           define _Py_get_current_process_id() (__readfsdword(0x20))
#           define _Py_get_current_thread_id()  (__readfsdword(0x24))

    That exploits the fact that Windows uses the FS/GS registers to
    store thread/process metadata.  Could I use a similar approach on
    FreeBSD to get the thread ID without the need for syscalls?

    (I technically don't need the thread ID, I just need to get some
     form of unique identifier for the current thread such that I can
     compare it to a known global value that's been set to the "main
     thread", in order to determine if I'm currently that thread or not.
     As long as it's unique for each thread, and static for the lifetime
     of the thread, that's fine.)

    The "am I the main thread?" comparison is made every ~50-100 opcodes,
    which is why it needs to have the lowest overhead possible.

    Regards,

        Trent.



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20130115205403.GA52904>