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