2012-09-12 98 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对象,并且不要忘记在完成后取消分配,通常是在创建的线程内。