我有這段代碼給我帶來麻煩。我知道所有的線程正在讀取相同的結構。但我不知道如何解決這個問題。pthread以獨特的struct作爲參數C
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int a,b;
} s_param;
void *
threadfunc(void *parm)
{
s_param *param2 = parm;
printf("ID:%d and v:%d\n",param2->a,param2->b);
pthread_exit(NULL);
}
int main(int argc, char **argv)
{
pthread_t thread[3];
int rc=0,i;
void * status;
for(i=0; i<3 ; ++i){
s_param param;
param.b=10;
param.a=i;
rc = pthread_create(&thread[i], NULL, threadfunc, ¶m); // !!!!
if(rc){
exit(1);
}
}
for(i=0; i<3 ; ++i){
pthread_join(thread[i],&status);
}
return 0;
}
輸出:
ID:2 and v:10
ID:2 and v:10
ID:2 and v:10
和我需要什麼:
ID:0 and v:10
ID:1 and v:10
ID:2 and v:10
's_param * param = thread [i];'應該是's_param * param =&thread [i];' – 2010-04-05 02:04:08