[英]Can syscall(SYS_gettid) block?
My understanding is that some if not all syscalls can be blocking.我的理解是,如果不是所有系统调用,一些系统调用可能会阻塞。 Is this a blocking call?这是阻塞电话吗? I want to obtain a unique thread id in a function that gets called repeatedly and is time-sensitive.我想在 function 中获得一个唯一的线程 id,它被重复调用并且对时间敏感。 I was going to do like so:我打算这样做:
//header.h
#define _GNU_SOURCE
#include <sys/syscall.h>
#ifdef SYS_gettid
#define gettid() syscall(SYS_gettid)
#else
#define gettid() 0
#endif
//file.c
#include "header.h"
...
void function()
{
pid_t thread = gettid();
//Logic based on thread
...
}
Here function will get called repeatedly and cannot block.这里 function 会被重复调用并且不能阻塞。 Perhaps I should use pthread_self()
and pthread_equal(t1, t2)
?也许我应该使用pthread_self()
和pthread_equal(t1, t2)
? Thanks.谢谢。
EDIT: I could equally well use either.编辑:我同样可以使用任何一个。 I understand they do not provide the same return values, but the logic I will perform on the thread id is to compare it to a set of known thread ids to basically figure out who is calling this.我知道它们不提供相同的返回值,但我将对线程 id 执行的逻辑是将其与一组已知的线程 id 进行比较,以基本上找出谁在调用它。 I have both the gettid() return value and the pthread_self() reutrn value saved off.我保存了 gettid() 返回值和 pthread_self() reutrn 值。
You should use pthread_self
, mostly because it's portable and syscall(SYS_gettid)
isn't, but also because typical implementations don't need to trap into the kernel at all.您应该使用pthread_self
,主要是因为它是可移植的,而syscall(SYS_gettid)
不是,还因为典型的实现根本不需要陷入 kernel 中。 For instance, on the machine where I'm typing this, there is a special hardware register called tpidr_el0
that stores a pointer to thread-specific data, and so pthread_self
can be just three instructions, with no privilege level change required:例如,在我输入这个的机器上,有一个名为tpidr_el0
的特殊硬件寄存器,它存储一个指向线程特定数据的指针,因此pthread_self
可以只是三个指令,不需要更改权限级别:
0000000000077870 <pthread_self>:
77870: d53bd040 mrs x0, tpidr_el0
77874: d11e4000 sub x0, x0, #0x790
77878: d65f03c0 ret
To be fair, a system call on this architecture is also just a handful of instructions, eg公平地说,这个架构上的系统调用也只是少数指令,例如
00000000000a67c0 <getpid>:
a67c0: d503245f bti c
a67c4: d2801588 mov x8, #0xac
a67c8: d4000001 svc #0x0
a67cc: d65f03c0 ret
but an assembly dump of the syscall stub does not show the hundreds or even thousands of cycles worth of costs hiding behind that svc
instruction.但是系统调用存根的汇编转储并没有显示隐藏在该svc
指令后面的数百甚至数千个周期的成本。 If you're doing something frequent and time-sensitive, not trapping into the kernel can be a huge win.如果您经常做一些时间敏感的事情,那么不陷入 kernel 可能是一个巨大的胜利。
I'd also recommend you think about reorganizing your code so that work comes in bigger batches and you don't need to ask "what thread am I on?"我还建议你考虑重新组织你的代码,这样工作就可以大批量进行,你不需要问“我在哪个线程上?” so often.很经常。 Operations not done at all are always fastest.根本没有完成的操作总是最快的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.