3 ms·
Very intriguing, thanks for the excellent slides. Is it possible to know the thread ID efficiently on Linux or other *NIX systems, using a similar fashion pres
by barosl 12y ago
Very intriguing, thanks for the excellent slides.
Is it possible to know the thread ID efficiently on Linux or other *NIX systems, using a similar fashion presented for Windows in the slides? I have no idea on how much calling pthread_self() every time impacts the performance, but it would be better if a faster method is available.
- ori_b 12y agopthread_self() pretty much returns a thread-local variable. Short of inlining the function to one mov instruction, I don't think it's possible to make it faster. (Source: http://koala.cs.pub.ro/lxr/glibc/nptl/pthread_self.c http://koala.cs.pub.ro/lxr/glibc/nptl/pthread_self.c and http://koala.cs.pub.ro/lxr/glibc/nptl/sysdeps/x86_64/tls.h#L172 http://koala.cs.pub.ro/lxr/glibc/nptl/sysdeps/x86_64/tls.h#L...)
- tachyonbeam 12y agoSpeculating here, but all that method needs to do is access some thread record struct. The big question is whether it does a context switch to access this struct in memory every time. Maybe the struct is in some read-only memory, and can be read from user space, but not written?
- dfox 12y agoOn i386 and amd64 on essentially all operating systems there is some kind of thread description structure that is accessible through one of segment registers which contains low-level thread context, some way to get to thread ID and user-accessible space for thread local variables (or pointer to such space). Getting some kind of thread ID is thus only about one "mov dest, [?S: some offset]", which is what both pthread_self() on linux and GetCurrentThreadId() on windows does (note that linux stores pointer to pthread_t in there, windows stores some opaque number that you have to convert to handle yourself if you need handle. The point is that in both cases the function does not do any kind of involved computation as would be the case if it had to traverse list of currently running threads). This mechanism is essentially the only reason why amd64 in long mode still has limited support (complete enough to implement this, nothing much more) for segment registers.
- trentnelson 12y agoAh, I just reviewed the slides... looks like I don't actually mention __readfsbase(), I thought I did. Basically, on amd64, you can just read the base address of one of the FS/GS segment registers and that'll be guaranteed to be unique amongst all threads in a given process. (Funnily enough that intrinsic doesn't (or didn't at the time) appear to be exposed by MSVC, so I just stuck with __readfsdword(0x48) on Windows.)