Linux thread id recycle strategy


Tags: c linux pthreads
标签: c linux pthreads

问题 (Question)

What's the recycle strategy of Linux thread ID ?

Linux process ID will not be reused immediately unless new PID get the max limitation and being rewinded.

When I use pthread_self() to get thread id, I got TIDs like 1028, 1034. I guess it is the inner "serial number" of threads in a process. So I guess it would be more appropriate to use a thread id recycle strategy like PID recycle strategy. But I am not quite sure whether it is true as to Linux pthread implementation.



当我用pthread_self()让线程ID,我所喜欢的1028,1034。我猜是线程的过程中内部的“编号”。所以我想这将是更适合使用的线程的ID循环策略如PID循环策略。但我不能肯定这是否是真的为Linux Pthread。

最佳答案 (Best Answer)

A threaded linux process has

  1. an OS pid shared by all threads within the process - use getpid
  2. each thread within the process has its own OS thread id - use gettid
  3. a pthreads thread id used internally by pthreads to identify threads when making various pthread related calls - use pthread_self and similar.

It can't be determine from your question if you trying to implement a "recycle strategy" or why you think you need to do so.


As an idle curiosity you can look through the linux pthread code but technically you have no reason to care. The POSIX spec basically just says the thread id is guaranteed to be unique within a process and is free to be reused after a thread dies.

Although implementations may have thread IDs that are unique in a system, applications should only assume that thread IDs are usable and unique within a single process. The effect of calling any of the functions defined in this volume of IEEE Std 1003.1-2001 and passing as an argument the thread ID of a thread from another process is unspecified. A conforming implementation is free to reuse a thread ID after the thread terminates if it was created with the detachstate attribute set to PTHREAD_CREATE_DETACHED or if pthread_detach() or pthread_join() has been called for that thread.


  1. 一个操作系统的PID的进程内部的线程共享使用getpid
  2. 在进程中的每个线程都有自己的操作系统线程ID使用gettid
  3. 一个pthreads的线程ID在内部使用pthreads识别线程时,制作各种线程相关的电话使用pthread_self类似的。



作为一个无聊的好奇你可以看看Linux Pthread代码,但事实上你没有理由去关心。POSIX规范基本上是说,线程ID保证在过程中是独一无二的,自由是一个线程死亡后重复使用。