[英]Start a thread inside a cpp file of a header file in C++ <process.h>
I have a class A
with a function void runThread()
to call new thread. 我有一个
class A
,带有函数void runThread()
来调用新线程。 This is my A.cpp
with struct SendInfo
and function void thread(...)
are not included in header file Ah
: 这是我的
A.cpp
具有struct SendInfo
和功能void thread(...)
未包含在头文件Ah
:
//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. 当在主功能,我调用
runThread()
的A object
,结果info.mess
是好的,但args->mess
没有字符串。 So what's my problem? 那我怎么了 and how to solve it?
以及如何解决?
You are using the local variable info
; 您正在使用局部变量
info
; as soon as runThread
exits, this variable goes out of scope and you must no longer access it, even from the other thread. 一旦
runThread
退出,此变量将超出范围,并且您不能再访问它,即使从另一个线程也是如此。
You need to ensure info
has a lifetime which extends until the end of your thread
function (or at least, until you've accessed it for the last time in thread
). 您需要确保
info
的生命周期可以延长到thread
函数结束(或至少直到您在thread
最后一次访问它为止)。
菲利普·肯德尔(Phillip Kendall)所说的,此外,在进行更改时要警惕广告的安全性-不仅要全球化info
,还应将其封装在A
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.