简体   繁体   English

将参数传递给线程

[英]passing arguments to a thread

I have a thread to which i wish to pass 3 arguments. 我有一个线程想要传递3个参数。 So, i put them in a struct as follows: 因此,我将它们放在一个结构中,如下所示:

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

I passed the arguments the following way: 我通过以下方式传递了参数:

 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));

But when i checked these values at the beginning of the thread itself, they were changed. 但是,当我在线程本身的开头检查这些值时,它们就被更改了。

 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
 }

Can anybody tell me why this happened? 有人可以告诉我为什么会这样吗?
Thanks in advance!! 提前致谢!!

You should not pass the address of a local object (ie created on stack) out of the function. 您不应将本地对象(即在堆栈上创建)的地址传递出该函数。 You should allocate it using malloc / new . 您应该使用malloc / new分配它。

The problem is that you allocated arg1 on the stack, and that memory got out of scope and reused before the thread started executing. 问题是您在堆栈上分配了arg1 ,并且内存超出范围并在线程开始执行之前被重用。 Allocate the arg object on the heap using malloc or new , and don't forget to de-allocate it after you're done, usually from within the thread you created. 使用mallocnew在堆上分配arg对象,并且别忘了在完成后通常从创建的线程中取消分配它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM