pthread_create 會多建立一個 thread 的原因
之前在執行某個客戶的案子時,被問到一個問題:「你說你們程式開了兩個thread,那為什麼透過 ps 指令觀察到的個數卻是 4 個呢?」(ps 的指令為 ps -L,可以透過 PID 和 LWP 這兩個欄位看出來),一時之間不知道怎麼回答。之後由同事 York 在 man pthreads找到了下面的答案。
Linux implementations of POSIX threads
Over time, two threading implementations have been provided by the
GNU C library on Linux:
LinuxThreads
This is the original Pthreads implementation. Since glibc
2.4, this implementation is no longer supported.
NPTL (Native POSIX Threads Library)
This is the modern Pthreads implementation. By comparison
with LinuxThreads, NPTL provides closer conformance to the
requirements of the POSIX.1 specification and better
performance when creating large numbers of threads. NPTL is
available since glibc 2.3.2, and requires features that are
present in the Linux 2.6 kernel.
從上面我們可以知道,Linux 在 pthread 上的實作方成兩種,LinuxThreads 和 NPTL,其中 NPTL 是比較新的實作方式。而在 LinuxThreads 的章節則提到了:
In addition to the main (initial) thread, and the threads that the program creates using pthread_create(3), the implementation creates a "manager" thread. This thread handles thread creation and termination. (Problems can result if this thread is inadvertently killed.)
這就是為什麼才呼叫兩次 pthread_create 卻產生了 4 個 thread 的原因(不要忘了本來的 main thread)。
文章技術內容就到這裡為止,接下來是個小提醒。York 他其實很早就查到了 manager thread 的理由自己的電腦上(Linux Mint 17)多做了實驗,發現根本沒有多一個 thread 啊,於是繼續挖掘,才找到了兩個不同實作方式的這件事。所以提醒自己和看本文的人,要養成追根究底的精神啊(話說我從小孩出生以後就愈來愈少深究技術類的資料了,這可不是好現象啊)
Linux implementations of POSIX threads
Over time, two threading implementations have been provided by the
GNU C library on Linux:
LinuxThreads
This is the original Pthreads implementation. Since glibc
2.4, this implementation is no longer supported.
NPTL (Native POSIX Threads Library)
This is the modern Pthreads implementation. By comparison
with LinuxThreads, NPTL provides closer conformance to the
requirements of the POSIX.1 specification and better
performance when creating large numbers of threads. NPTL is
available since glibc 2.3.2, and requires features that are
present in the Linux 2.6 kernel.
從上面我們可以知道,Linux 在 pthread 上的實作方成兩種,LinuxThreads 和 NPTL,其中 NPTL 是比較新的實作方式。而在 LinuxThreads 的章節則提到了:
In addition to the main (initial) thread, and the threads that the program creates using pthread_create(3), the implementation creates a "manager" thread. This thread handles thread creation and termination. (Problems can result if this thread is inadvertently killed.)
這就是為什麼才呼叫兩次 pthread_create 卻產生了 4 個 thread 的原因(不要忘了本來的 main thread)。
文章技術內容就到這裡為止,接下來是個小提醒。York 他其實很早就查到了 manager thread 的理由自己的電腦上(Linux Mint 17)多做了實驗,發現根本沒有多一個 thread 啊,於是繼續挖掘,才找到了兩個不同實作方式的這件事。所以提醒自己和看本文的人,要養成追根究底的精神啊(話說我從小孩出生以後就愈來愈少深究技術類的資料了,這可不是好現象啊)
留言
張貼留言