2012-05-10 34 views
14

我對通過在pthread_create()創建新的線程,一個簡單的問題:PID爲新的線程

當我打印PID主線程和子線程的,它們是相同的,而(從GETPID()獲得)當我使用htop linux實用程序來顯示pid時,它們是不同的。任何人都可以向我解釋這個嗎?謝謝!!

[email protected]:~/LPI$ ./pthr_create 
-------------------------------------- 
main thread: pid: 4845, ppid: 3335 
child thread: pid: 4845, ppid: 3335 

HTOP示出: Screenshot of the htop application showing a list of processes.

+0

線程不是進程!一個進程由一個或多個線程組成。 –

回答

19

Linux將pthreads()設置爲Light-Weight-Processes,因此它們會分配一個PID。

更多信息可以http://www.linuxforu.com/2011/08/light-weight-processes-dissecting-linux-threads/

發現還有一個例子,如何獲得LWP-PID爲你的線程。

#include <stdio.h> 
#include <syscall.h> 
#include <pthread.h> 

int main() 
{ 
    pthread_t tid = pthread_self(); 
    int sid = syscall(SYS_gettid); 
    printf("LWP id is %d\n", sid); 
    printf("POSIX thread id is %d\n", tid); 
    return 0; 
} 
2

線程同時具有進程ID,從GETPID()系統調用返回,線程ID,由gettid()返回。對於在main()下執行的線程,這些將是相同的。我不知道哪一個htop正在報告,你應該檢查文檔。