[英]Creating N number of threads
我編寫了以下代碼來創建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
問題出在以下幾行:
retVal=pthread_create(&thread[i],NULL,threadFunction,(void *)&i);
不要傳遞i
的地址,因為i
在main函數中不斷變化。 而是傳遞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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.