gpt4 book ai didi

c++ - 将参数传递给线程

转载 作者:行者123 更新时间:2023-11-27 23:21:46 25 4
gpt4 key购买 nike

我有一个线程,我希望向其传递 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
}

谁能告诉我为什么会这样?
提前致谢!!

最佳答案

您不应该将本地对象(即在堆栈上创建的)的地址传递到函数之外。您应该使用 malloc/new 分配它。

关于c++ - 将参数传递给线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12390506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com