我对linux内核调度有疑问。
我们知道,通常,linux维护当前最大的pid。如果我们想要启动一个新进程,内核将使用那个最大的id。因此,如果我们终止并重新启动新进程,则进程ID不是顺序的。 Linux将使用最大的id,直到达到限制。
但我的问题是linux如何决定线程ID。 比如,进程A和B正在运行。进程A崩溃但进程B正在生成新线程。进程B是否只重用属于进程A的旧tid,或者进程B也将使用最大的id作为tid。哪种情况更常见?我们有文件吗?
感谢。
答案 0 :(得分:0)
内核设置最大数量的进程/线程ID,并在线程被垃圾回收时简单地回收标识符。因此,如果进程B生成足够的线程,它将最终从进程A回收线程ID,假设它已被正确销毁
编辑:以下是一些可以为您提供更具体答案的链接
pid和tid之间的区别 https://stackoverflow.com/a/8787888/5768168
"线程和进程ID的值范围是多少?" what is the value range of thread and process id?
" Linux PID回收" https://stackoverflow.com/a/11323428/5768168
"流程识别" https://en.wikipedia.org/wiki/Process_identifier#Unix-like
" Linux内核:进程" https://www.win.tue.nl/~aeb/linux/lk/lk-10.html
答案 1 :(得分:0)
It sounds like you need to run your threads in with a PTHREAD_CREATE_JOINABLE
attribute passed to pthread_create()
, then have one reaper thread in your process dedicated to using pthread_join()
or pthread_tryjoin()
to wait for terminated threads. Rather than having an outside process trying to sort it out, have your process record the PID/TID pair after pthread_create()
succeeds and have the reaper thread remove the pair when it detects the thread has terminated.
I typically combined that with a main thread that did nothing but spawn the thread-creation and reaper threads, then wait for a termination signal and terminate the thread-creator and reaper. The thread-creator stops immediately when signaled, the reaper stops when no more unterminated threads are running, the main thread terminates when both the thread-creator and reaper threads can be pthread_join()
'd. Since the main thread's so simple it's unlikely to crash, which means most crashes in work threads simply deliver them to the reaper. If you want absolute certainty, your outside process should be the one to start your main process, then it can use wait()
or it's siblings to monitor whether the main process has terminated (normally or by crashing).