2017-06-13 115 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')。 –