2012-05-01 7 views
10

모두리눅스 커널 3.2에서 pthread는 어떻게 구현 되었습니까?

아래 코드는 "Unix 환경의 고급 프로그래밍"에서 가져온 것으로 새로운 스레드를 만들고 주 스레드와 새 스레드의 프로세스 ID와 스레드 ID를 인쇄합니다.

리눅스에서이 코드의 출력은 두 스레드가 프로세스 ID가 다르다는 것을 나타냅니다. pthread는 스레드를 에뮬레이트하기 위해 경량 프로세스를 사용하기 때문입니다. 하지만 우분투 12.04에서이 코드를 실행하면 커널 3.2가 나오고 같은 PID를 출력합니다.

그래서 새로운 리눅스 커널이 pthread의 내부 구현을 변경합니까? 리눅스 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; 
} 
+0

또한 참조하십시오 : http://stackoverflow.com/questions/5514464/difference-between-pthread-and-fork-on-gnu-linux –

+3

위키 피 디아는 커널 2.6에서 NPTL을 만든 스위치에 대한 기사를 가지고 있습니다. http://en.wikipedia.org/wiki/Native_POSIX_Thread_Library 및 이전 쓰레딩 모델 인 LinuxThreads의 단점을 설명하는 짧은 기사 : http://en.wikipedia.org/wiki/LinuxThreads –

답변

19

는 특별한 플래그 CLONE_THREADclone 콜을 사용합니다.

documentationclone 시스템 호출을 참조하십시오.

CLONE_THREAD (이후 리눅스 2.4.0-TEST8)

CLONE_THREAD가 설정되어있는 경우, 아이가 호출 된 프로세스와 같은 스레드 그룹에 배치됩니다. CLONE_THREAD 토론의 나머지 부분을 더 읽기 쉽게하기 위해 "스레드"라는 용어는 스레드 그룹 내의 프로세스를 나타내는 데 사용됩니다.

스레드 그룹은 스레드 그룹의 POSIX 스레드 개념을 지원하기 위해 Linux 2.4에서 추가 된 기능으로 은 단일 PID을 공유합니다. 내부적으로이 공유 PID는 스레드 그룹에 대한 소위 스레드 그룹 식별자 (TGID)입니다. 리눅스 2.4부터 getpid (2) 호출은 호출자의 TGID를 반환한다.

개의 스레드가 동일한 프로세스 ID를 공유하기 때문에 실제로 Linux는 change its thread implementation을 수행합니다. 전자는 대부분 쓸모 있지만, LinuxThreadsNative POSIX Thread Library(NPTL) :

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). 
+0

정말 고마워요! 너는 내게 옳은 것을 주었다! – jiluo

4

리눅스는 보통의 pthreads의 두 가지 구현을 사용합니다. 커널 2.6은 SUSv3에 훨씬 더 잘 부합하는 NPTL을 제공하며, 특히 스레드가 많은 경우 더 잘 수행됩니다.
당신은 명령을 사용하여 쉘에서의 pthreads의 구체적인 구현을 조회 할 수 있습니다

getconf GNU_LIBPTHREAD_VERSION

당신은 또한 The Linux Programming Interface에 대한보다 상세한 구현 차이를 얻을 수 있습니다.