2016-08-02 21 views
3

絕對奇怪的情況在創建線程,這裏的測試代碼:的Linux 2.6.30 uClibc的0.9.29在pthread_create 2胎面insted的只是一個

#include <stdint.h>   /* C99 types */ 
#include <stdbool.h>  /* bool type */ 
#include <stdio.h>   /* printf, fprintf, snprintf, fopen, fputs */ 

#include <string.h>   /* memset */ 
#include <signal.h>   /* sigaction */ 
#include <time.h>   /* time, clock_gettime, strftime, gmtime */ 
#include <sys/time.h>  /* timeval */ 
#include <unistd.h>   /* getopt, access */ 
#include <stdlib.h>   /* atoi, exit */ 
#include <errno.h>   /* error messages */ 
#include <math.h>   /* modf */ 
#include <assert.h> 

#include <sys/socket.h>  /* socket specific definitions */ 
#include <netinet/in.h>  /* INET constants and stuff */ 
#include <arpa/inet.h>  /* IP address conversion stuff */ 
#include <netdb.h>   /* gai_strerror */ 

#include <pthread.h> 
void thread_up(void) { 
     printf("thread ....\n"); 
     int loop=0; 
     while(loop<=7) 
     { 
       printf("loop...\n"); 
       sleep(10); 
       loop++; 
     } 
     printf("Exit loop\n"); 
} 
int main() 
{ 
pthread_t thrid_up=0; 

     int i = pthread_create(&thrid_up, NULL, (void * (*)(void *))thread_up, NULL); 
     if (i != 0) { 
       printf("ERROR: [main] impossible to create upstream thread\n"); 
       exit(1); 
     } 
     while(1) 
     { 
       sleep(10); 
     } 

} 

代碼產生的ps命令輸出如下(後./test &發射):

30214 root  704 S ./test 
30215 root  704 S ./test 
30216 root  704 S ./test 

任何提示?

+1

'ps'默認情況下不顯示線程,AFAIK。你是否用任何特殊的旗幟運行它?你確定你不只是運行你的程序的三個實例嗎?如果你將調用放到'pthread_create()'中,會發生什麼? – Hasturkun

+0

我看不出有任何理由解決了這個問題。這是一個完全有效的問題。有人欠這個人回票。 –

回答

4

只是一個說明。 man 7 pthreads

的LinuxThreads

這種實現的顯着的特點如下:

  • 除了主(初始)螺紋,並且所述 程序創建使用pthread_create(3)螺紋,所述執行 創建一個「經理」線程。此線程處理線程創建 並終止。 (如果線程 無意中死亡,則可能導致問題。)
  • 線程不共享進程ID。 (實際上,LinuxThreads 線程實現爲共享比平常更多信息 但不共享公共進程ID的進程。) LinuxThreads線程(包括管理器線程)可見爲 單獨進程使用ps(1)

不管這個文檔是關於你的Glibc版本uClibc中可能會使用Linux線程並行線程作爲「後臺」。所以在技術上你的代碼可能會創建三個調度實體。

但首先你必須確保ps能夠打印線程,不僅僅是進程並且在探測過程中仔細檢查你的程序只有一個啓動的實例。

P.S.你也應該檢查你的uClibc是否真的使用LinuxThreads而不是NPTL。所以IMO有機會觀察三個線程,但它非常小。

+0

也許你是對的,我更新了我的答案和鏈接來源。 +1 – LPs

+2

你爲什麼不繼續閱讀(並複製/粘貼)該頁面? *線程不共享進程ID。 (實際上,LinuxThreads 線程實現爲共享比平常更多信息 但不共享公共進程ID的進程。) LinuxThreads線程(包括管理器線程)可見爲 單獨的進程使用ps(1) 。* –

+0

我的遺漏感謝您的糾正! – Sergio

2

ps向您顯示進程,而不是線程。

也許你纔開始使用./test &

爲了測試它使用殺死所有過程3次你的應用程序:killall test

所以重新開始你的過程和看到的輸出:ps -A | grep test 它會告訴你1個實例的test

然後使用:ps -eLf | grep test你會看到test的線程。


編輯

相關的@Serhio答案,那就是可能是正確的,尋找到uClibc的源在this link就可以發現,進入的libpthread目錄,即Linux線程的使用,所以線程管理器將添加。

+0

*「'ps'顯示你的過程,而不是線程。」*現在,是的。 LinuxThreads並非如此。每個線程都有自己的PID(是,PID),這就是OP看到他的輸出的原因。 –

+0

@JonathonReinhart很高興知道。謝謝。我今天學到一些東西;) – LPs

0

是的...對(@Serhio和@LPs)...我的uClibc使用我剛剛檢查過的管理器。

不幸的是,由於tyny linux嵌入式環境,我的ps非常糟糕。

+1

因此請檢查@Serhio答案是否正確。 – LPs