I am working on a multithreaded application in which a client program generates request threads that send strings to a data server program, which answers by sending strings back. Unfortunately, I am having trouble passing data from the client's main function to the function that is invoked by each request thread. In main, I get the request threads going like this (some previous variable declarations not shown):
for(int j = 0; j < persons.size(); j++){ //requests deal with imaginary people
thread_args* dat = new thread_args;
strcpy(dat->str, persons[j].c_str());
cout << "***I COPIED " << dat->str << " INTO dat->str!!!"<<endl; //prints as expected
pthread_create(&request_thread[j],NULL,&deposit_requests, &dat);
}
Specifically, the structure I am using to pass things with the threads looks like this:
typedef struct str_thdata{
char str[100];
} thread_args;
Now, in the cout within main ("***I COPIED..."), everything is well and good. The correct value is indeed copied in. When I get to the actual function invoked by the thread, though, the string is lost:
void* deposit_requests(void* str_arg){
for(int i = 0; i < req_per_person; i++){
thread_args* data = (thread_args*)str_arg;
cout << "data->str is " << data->str << endl; //empty string!!!
...
}
}
My only idea is that maybe something is going out of scope? Unless I am being blind here, I don't see where it would happen. Or maybe I need additional casting somewhere? I tried a few variations within the second cout (e.g., using ((thread_args*)data)->str) ), but that didn't seem to work. What is happening to my character array?
That &dat you pass in pthread_create is the address of a pointer to a thread_args struct, not the address of a thread_args struct.
Pass dat without the & to pthread_create, and then your code for deposit_requests should run fine.
pthread_create(&request_thread[j],NULL,&deposit_requests, dat);