I have a class A with a functionvoid runThread() to call new thread. This is my A.cpp with struct SendInfo and function void thread(...) are not included in header file A.h:
//A.cpp
struct SendInfo{
int a;
std::string mess;
SendInfo(int _a, std::string _mess){
a = _a;
mess = _mess;
}
};
void thread(SendInfo* args){
std::cout << args->mess << std::endl; // Result here is nothing :-?
}
void A::runThread(){
SendInfo info(10,"dump_string");
std::cout << info.mess << std::endl; // Result here is "dump_string"
_beginthread((void(*)(void*))thread, 0, &info);
}
When in main function, i call runThread() of A object, the result of info.mess is good, but args->mess have no string. So what’s my problem? and how to solve it?
You are using the local variable
info; as soon asrunThreadexits, this variable goes out of scope and you must no longer access it, even from the other thread.You need to ensure
infohas a lifetime which extends until the end of yourthreadfunction (or at least, until you’ve accessed it for the last time inthread).