0

我有class A一个函数void runThread() 来调用新线程。这是我A.cpp的 withstruct SendInfo和函数void thread(...)不包含在头文件中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);
}

在 main 函数中,我调用runThread()ofA object时,结果info.mess很好,但args->mess没有字符串。那我的问题是什么?以及如何解决?

4

2 回答 2

4

您正在使用局部变量info;一旦runThread退出,这个变量就会超出范围,你不能再访问它,即使是从另一个线程。

您需要确保info有一个生命周期,直到您的thread函数结束(或者至少,直到您最后一次在 中访问它thread)。

于 2012-07-04T08:25:34.823 回答
0

Phillip Kendall 所说的,另外,当你做出改变时要警惕广告安全——不要只是全球化info,把它封装在A.

于 2012-07-04T08:33:45.510 回答