[英]How does pthread implemented in linux kernel 3.2?
所有,
下面的代碼來自“Unix環境中的高級編程”,它創建一個新線程,並打印主線程和新線程的進程ID和線程ID。
在本書中,它表示在linux中,此代碼的輸出將顯示兩個線程具有不同的進程ID,因為pthread使用輕量級進程來模擬線程。 但是當我在Ubuntu 12.04中運行此代碼時,它有內核3.2,打印相同的pid。
那么,新的linux內核是否會改變pthread的內部實現?
#include "apue.h"
#include <pthread.h>
pthread_t ntid;
void printids(const char *s) {
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\n",
s, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
}
void *thread_fn(void* arg) {
printids("new thread: ");
return (void *)0;
}
int main(void) {
int err;
err = pthread_create(&ntid, NULL, thread_fn, NULL);
if (err != 0)
err_quit("can't create thread: %s\n", strerror(err));
printids("main thread: ");
sleep(1);
return 0;
}
在Linux上, pthread
使用帶有特殊標志CLONE_THREAD
的clone
系統調用。
請參閱clone
syscall的文檔 。
CLONE_THREAD(自Linux 2.4.0-test8開始)
如果設置了CLONE_THREAD,則子節點與調用進程放在同一個線程組中。 為了使CLONE_THREAD的剩余討論更具可讀性,術語“線程”用於指代線程組內的進程。
線程組是Linux 2.4中添加的一項功能,用於支持共享單個PID的一組線程的POSIX線程概念。 在內部,該共享PID是線程組的所謂線程組標識符(TGID)。 從Linux 2.4開始,對getpid(2)的調用返回調用者的TGID。
事實上,Linux確實改變了它的線程實現 ,因為POSIX.1要求線程共享相同的進程ID。
In the obsolete LinuxThreads implementation, each of the threads in a process has a different process ID. This is in violation of the POSIX threads specification, and is the source of many other nonconformances to the standard; see pthreads(7).
Linux通常使用兩種pthread實現: LinuxThreads和Native POSIX Thread Library(NPTL) ,盡管前者基本上已經過時了。 2.6中的內核提供了NPTL,它提供了與SUSv3更接近的一致性,並且在有許多線程時表現更好。
您可以使用命令在shell下查詢pthread的具體實現:
getconf GNU_LIBPTHREAD_VERSION
您還可以在Linux編程接口中獲得更詳細的實現差異。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.