gpt4 book ai didi

c++ - 创建线程时丢失成员数据

转载 作者:太空宇宙 更新时间:2023-11-04 05:14:23 24 4
gpt4 key购买 nike

我发现很难解释这个问题,所以我会贴出代码并解释发生了什么,然后问如何让它做我想做的事。首先,我在子进程中创建一个线程:

pid_t childpid = fork();

if(childpid == -1){
cout << "Failed to fork." << endl;
}
else if(childpid == 0){
//request threads
pthread_t p1, p2, p3;

struct arg_struct args1, args2, args3;

args1.name = "data Joe Smith";
args1.num_req = n;
args1.buff_size = b;
pthread_create(&p1, NULL, &mythreadfunc, (void *)&args1);
}

这是struct arg_struct:

struct arg_struct{
string name;
int num_req;
int curr_value;
int buff_size;
};

mythreadfunc:

void *mythreadfunc(void *arguments){ 
struct arg_struct *args = (struct arg_struct *)arguments;
string local_name = args->name;
int local_num_req = args->num_req;
//request new thread
RequestChannel chan("control", RequestChannel::CLIENT_SIDE);
cout << "done." << endl;
string reply1 = chan.send_request("newthread");

cout << "Reply to request 'newthread' is " << reply1 << "'" << endl;

RequestChannel chan2(reply1, RequestChannel::CLIENT_SIDE);

cout<<"local_name: "<<local_name<<endl; //returns incorrect value***
cout<<"local_num_req: "<<local_num_req<<endl; //returns incorrect value***

//close up all channels
string reply2 = chan2.send_request("quit");
cout << "Reply to request 'quit' is '" << reply2 << "'" << endl;
string reply3 = chan.send_request("quit");
cout << "Reply to request 'quit is '"<< reply3 << "'" << endl;
}

在利用local_namelocal_num_req 的两行中,有问题。我编译得很好,但是这两个变量每次似乎总是存储不同的东西。有时它工作正常,而有时它们持有垃圾值并且程序永远不会执行它们(或任何后续)。我尝试使用没有局部变量的原始名称(即 args->name),但问题是一样的。我最好的猜测是我的 args_struct 错误地处理了变量,但我不知道为什么它只会在部分时间失败。

如何在 mythreadfunc 中获得正确的变量值?

最佳答案

在堆上为您的新线程创建参数,它超出了调用函数的范围,因此对于您的线程使用无效:

struct arg_struct *arg1 = new arg_struct;

args1->num_req = n;
// etc...

pthread_create(&p1, NULL, &mythreadfunc, (void *) args1);

关于c++ - 创建线程时丢失成员数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11704842/

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