From owner-freebsd-hackers@FreeBSD.ORG Tue Jan 15 20:55:16 2013 Return-Path: Delivered-To: freebsd-hackers@freebsd.org Received: from mx1.freebsd.org (mx1.FreeBSD.org [8.8.178.115]) by hub.freebsd.org (Postfix) with ESMTP id AC42146C for ; Tue, 15 Jan 2013 20:55:16 +0000 (UTC) (envelope-from trent@snakebite.org) Received: from exchange.liveoffice.com (exchla3.liveoffice.com [64.70.67.188]) by mx1.freebsd.org (Postfix) with ESMTP id 990787D7 for ; Tue, 15 Jan 2013 20:55:16 +0000 (UTC) Received: from EXHUB02.exchhosting.com (192.168.11.214) by exhub08.exchhosting.com (192.168.11.106) with Microsoft SMTP Server (TLS) id 8.3.213.0; Tue, 15 Jan 2013 12:54:06 -0800 Received: from localhost (35.8.247.10) by exchange.liveoffice.com (192.168.11.214) with Microsoft SMTP Server id 8.3.213.0; Tue, 15 Jan 2013 12:54:05 -0800 Date: Tue, 15 Jan 2013 15:54:03 -0500 From: Trent Nelson To: Subject: Getting the current thread ID without a syscall? Message-ID: <20130115205403.GA52904@snakebite.org> MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Disposition: inline User-Agent: Mutt/1.5.21 (2010-09-15) X-BeenThere: freebsd-hackers@freebsd.org X-Mailman-Version: 2.1.14 Precedence: list List-Id: Technical Discussions relating to FreeBSD List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Tue, 15 Jan 2013 20:55:16 -0000 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 # 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.