I find it hard to explain the problem, so I’ll post the code and explain what happens, and then ask how to make it do what I want. Firstly, I create a thread within a child process:
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);
}
This is the struct arg_struct:
struct arg_struct{
string name;
int num_req;
int curr_value;
int buff_size;
};
And the 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;
}
In the two lines that utilize local_name and local_num_req, there are problems. I compile fine, but the two variables always seem to store something different each time. Sometimes it works properly, while sometimes they hold garbage values and the program never executes them (or anything following). I tried to use the original names (i.e. args->name) without the local variables, but the problem is the same. My best guess is that my args_struct handles the variables wrong, but I don’t know why it would only fail part of the time.
How can I have the correct variable values in the mythreadfunc?
Create the argument for your new thread on the heap, it’s going out of scope in the calling function and so isn’t valid for use by your thread(s):