Aqu*_*irl 6 c linux multithreading pthreads
该引用来自pthread_self()的手册页.
那么,在什么基础上我应该决定是否应该使用pthread_self或gettid确定哪个线程正在运行该函数?
两者都不便携.
为什么有两个不同的函数来获取线程ID?
P.P*_*.P. 14
那么,在什么基础上我应该决定是否应该使用pthread_self或gettid来确定哪个线程正在运行该函数?
pthread_self()只要您想在应用程序中识别线程,就应该始终使用它.gettid() 可以用于某些目的,如果你知道它是Linux.例如,gettid()可用于获取特定于线程的种子(用于srand())的种子.
两者都不便携.
这不完全正确.gettid()不可移植,因为它是一个Linux特定的功能.但pthread_self()只要您不对其表示做任何假设,它就是可移植的.
例如,以下内容不可移植.
printf("Thread ID is: %ld", (long) pthread_self());
Run Code Online (Sandbox Code Playgroud)
因为不能保证任何东西pthread_self()都是某种整数.但
pthread_t my_tid; //filled elsewhere
pthread_t tid = pthread_self();
if( pthread_equal(my_tid, tid) ) {
/* do stuff */
}
Run Code Online (Sandbox Code Playgroud)
是完全便携的.
前者不可移植,因为它假定线程id是整数而后者不是.
为什么有两个不同的函数来获取线程ID?
它们不是获得相同价值的两种不同方式.一个(pthread_self()由线程库(pthreads)提供而另一个(gettid()是特定于OS的函数.不同的OS可能提供不同的接口/系统调用来获取类似的线程ID gettid().因此您不能依赖于gettid()便携式应用程序.
小智 6
pthread_self() returns the process-wide unique pthread-id.
gettid()返回(特定于pthread实现)系统范围的唯一thread-id(在Linux上).
the TID(thread id) returned by gettid() is unique inside a process
Run Code Online (Sandbox Code Playgroud)
是.
(or inside a program with multiple processes,
Run Code Online (Sandbox Code Playgroud)
是.
inside a process, different thread has different thread id.
Run Code Online (Sandbox Code Playgroud)
是.
the TID returned by pthread_self() is unique across processes,
Run Code Online (Sandbox Code Playgroud)
没有.
different thread has different TID on the same machine at the same time.
Run Code Online (Sandbox Code Playgroud)
是的,在同一个过程中,整个机器都没有.
由于gettid()是特定于Linux的,因此不可移植,因此系统广泛识别pthread的唯一方法是使用getpid()返回的(系统范围唯一的)父进程id及其(进程范围内唯一的)pthread- id由pthread_self()返回.