Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

linux - What is the difference between pthread_self() and gettid()? Which one should I use?

I'm trying to set the CPU affinity of threads on Linux. I'd like to know which one of the following approaches is recommended:

  1. Get thread id using pthread_self()

    Set CPU affinity using pthread_setaffinity_np(....) by passing the thread id as an argument

  2. Get thread id using the gettid() call

    Set CPU affinity using sched_setaffinity(....) by passing the thread id in the place of the process id

P.S: After setting the CPU affinity, I intend to increase the scheduling priority of the thread.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

They are not the same. Here are some bits I collected from TLPI (I couldn't find a large-enough block that completely describes this). If you're in a hurry you probably want just the last part.

gettid

Linux 2.4 introduced a new system call, gettid(), to allow a thread to obtain its own thread ID.

Each thread within a thread group is distinguished by a unique thread identifier. A thread ID is represented using the same data type that is used for a process ID, pid_t. Thread IDs are unique system-wide, and the kernel guarantees that no thread ID will be the same as any process ID on the system, except when a thread is the thread group leader for a process.

pthread_self

Each thread within a process is uniquely identified by a thread ID. A thread can obtain its own ID using pthread_self().

The pthread_equal() function is needed to compare thread ids because the pthread_t data type must be treated as opaque data.

In the Linux threading implementations, thread IDs are unique across processes. However, this is not necessarily the case on other implementations, and SUSv3 explicitly notes that an application can’t portably use a thread ID to identify a thread in another process.

gettid vs pthread_self

POSIX thread IDs are not the same as the thread IDs returned by the Linux-specific gettid() system call. POSIX thread IDs are assigned and maintained by the threading implementation. The thread ID returned by gettid() is a number (similar to a process ID) that is assigned by the kernel.

I would go with pthread_setaffinity_np but be aware that the manual says:

These functions are implemented on top of the sched_setaffinity(2)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...