【发布时间】: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
【问题讨论】:
-
您将变量
i的相同地址传递给线程工作者。当线程访问指针所指的值时,主循环已经设置了i = 0。
标签: c multithreading posix