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
您传递变量'i'的相同的地址到线程工人。当线程访问指针引用的值时,主循环已经设置了'i = 0'。 –
[pthread \ _create:传递一个整数作为最后一个参数]的可能重复(https://stackoverflow.com/questions/19232957/pthread-create-passing-an-integer-as-the-last-argument) – Stargateur