2012-09-12 140 views
0

我有一個線程,我希望傳遞3個參數。所以,我把它們放在一個結構如下:將參數傳遞給線程

struct arg 
{ 
time_t time1; 
float name1; 
time_t quantum1; 
}; 

我傳遞的參數方式如下:

arg arg1; 
arg1.time1=(time_t)(int)job.peek(); //job.peek() was 3 
cout<<"job time is "<<arg1.time1<<endl; //this output 3 

arg1.name1=(float)(int)job.returnname(NULL); //job.returnname() was 1 
cout<<"job name is "<<arg1.name1<<endl;// this output 1 

arg1.quantum1=quantum; //quantum was 7 
cout<<"quantum is "<<arg1.quantum1<<endl;//this output 7 

pthread_create(&thread1, NULL, func3, (void*)(&arg1)); 

但是,當我在螺紋本身的開始檢查這些值,它們被改變。

void* timer(void *argum) 
{ 
arg *arg1= (arg*)argum; 
cout<<"PROCESS "<<arg1->name1<<" HAS ENTERED THE TIMER"<<endl; //this output arg1->name1 as 1.4013e-45 
cout<<"Time remaining for process is "<<arg1->time1<<endl; //this output arg1->time1 as -1218381144 
cout<<"quantum is "<<arg1->quantum1<<endl; //this output arg1->quantum1 as 5 
} 

有人可以告訴我爲什麼會發生這種情況嗎?
在此先感謝!

+1

猜測'arg1'在'pthread_create()'調用後的某個點被銷燬。你能完成圍繞'pthread_create()'調用的範圍嗎?調用'pthread_create()'之後'arg1'是否超出範圍? – hmjd

回答

2

您不應該將本地對象的地址(即在堆棧上創建)傳遞出該函數。您應該使用malloc/new進行分配。

2

問題是您在堆棧上分配了arg1,並且該內存超出了範圍並在線程開始執行之前重新使用。使用mallocnew在堆上分配arg對象,並且不要忘記在完成後取消分配,通常是在創建的線程內。