繁体   English   中英

创建N个线程

[英]Creating N number of threads

我编写了以下代码来创建N个线程,并打印每个线程的线程ID。

#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。 但是在输出中我看到所有线程的值均为零,无法理解,有人可以解释一下。

  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

问题出在以下几行:

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

不要传递i的地址,因为i在main函数中不断变化。 而是传递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);


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM