J'ai écrit le code suivant pour créer N nombre de threads et imprimer l'ID de thread de chaque thread.Création d'un nombre N de threads
#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);
}
l'argument je passe à chaque fil est un compteur qui incrémente i de 0 à n-1 pour chaque nouveau thread. Mais tandis qu'à la sortie, je vois que j'ai la valeur zéro pour tous les threads, pas capable d'undestand, quelqu'un peut-il expliquer s'il vous plaît.
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
Vous passez la même adresse de la variable 'I' au travailleur de fil. Lorsque les threads accèdent à la valeur référencée par le pointeur, la boucle principale a déjà défini 'i = 0'. –
Copie possible de [pthread \ _create: passage d'un entier comme dernier argument] (https://stackoverflow.com/questions/19232957/pthread-create-passing-an-integer-as-the-last-argument) – Stargateur