【问题标题】:Creating N number of threads创建 N 个线程
【发布时间】:2017-06-13 10:02:28
【问题描述】:

我写了下面的代码来创建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

【问题讨论】:

标签: c multithreading posix


【解决方案1】:

问题出在下面一行:

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

不要传递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);


}

【讨论】:

  • 如果intvoid * 的大小不同,您需要分别制作(void *)(intptr_t)i= (int)(intptr_t)arg;intptr_t&lt;stdint.h&gt; 中定义(如果包含&lt;inttypes.h&gt;,则会自动包含)。
猜你喜欢
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 2021-06-07
  • 2021-12-30
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多