2017-06-13 57 views
0

我寫了下面的代碼來創建N個線程並打印每個線程的線程ID。創建N個線程

#include<stdio.h> 
#include<pthread.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <sys/syscall.h> 
#include <unistd.h> 


void *threadFunction (void *); 

int main (void) 
{ 

    int n=0,i=0,retVal=0; 
    pthread_t *thread; 

    printf("Enter the number for threads you want to create between 1 to 100 \n"); 
    scanf("%d",&n); 

    thread = (pthread_t *) malloc (n*sizeof(pthread_t)); 

    for (i=0;i<n;i++){ 
     retVal=pthread_create(&thread[i],NULL,threadFunction,(void *)&i); 
     if(retVal!=0){ 
      printf("pthread_create failed in %d_th pass\n",i); 
      exit(EXIT_FAILURE);   
     } 
    } 

    for(i=0;i<n;i++){ 
     retVal=pthread_join(thread[i],NULL); 
      if(retVal!=0){ 
       printf("pthread_join failed in %d_th pass\n",i); 
       exit(EXIT_FAILURE);   
      } 
    } 

} 

void *threadFunction (void *arg) 
{ 
    int threadNum = *((int*) arg); 

    pid_t tid = syscall(SYS_gettid); 

    printf("I am in thread no : %d with Thread ID : %d\n",threadNum,(int)tid); 


} 

爭我傳遞給每個線程是一個計數器i從0到n-1遞增爲每個新的線程。 雖然在輸出我看到我的價值爲零的所有線程,無法undestand,請有人請解釋。

Enter the number for threads you want to create between 1 to 100 
    5 
    I am in thread no : 0 with Thread ID : 11098 
    I am in thread no : 0 with Thread ID : 11097 
    I am in thread no : 0 with Thread ID : 11096 
    I am in thread no : 0 with Thread ID : 11095 
    I am in thread no : 0 with Thread ID : 11094 
+2

您傳遞變量'i'的相同的地址到線程工人。當線程訪問指針引用的值時,主循環已經設置了'i = 0'。 –

+0

[pthread \ _create:傳遞一個整數作爲最後一個參數]的可能重複(https://stackoverflow.com/questions/19232957/pthread-create-passing-an-integer-as-the-last-argument) – Stargateur

回答

1

問題在於以下行:

retVal=pthread_create(&thread[i],NULL,threadFunction,(void *)&i); 

不通過的i的地址,i保持在主函數變化。相反,在線程函數中使用並傳遞我的值和類型轉換。

對於實施例,傳遞值象下面這樣:

retVal=pthread_create(&thread[i],NULL,threadFunction,(void *)i); 

在如下線程功能的訪問:

void *threadFunction (void *arg) 
{ 
    int threadNum = (int)arg; 

    pid_t tid = syscall(SYS_gettid); 

    printf("I am in thread no : %d with Thread ID : %d\n",threadNum,(int)tid); 


} 
+0

您如果'int'和'void *'的大小不同,我們會分別使用'(void *)(intptr_t)i'和'=(int)(intptr_t)arg;'。 'intptr_t'在''中定義(如果包含'',則會自動包含'intptr_t')。 –