今天写一个unit test, 需要在子线程跑一个tcp客户端,来验证服务端功能:
ConsoleUploadFile::ConsoleUploadFile()
{
... ...
std::thread( &ConsoleUploadFile::uploadFile, this);
}
很奇怪的是,代码运行到std::thread(...)这句就崩溃了,还没有跑子线程绑定的函数uploadFile,我开始怀疑不能在构造函数中开线程,就另写了一个成员函数,但也是运行到std::thread(..)就崩溃。google了一番,没有进展,只能靠调试了,崩溃的现场是这样的:
libc++.1.dylib`std::__1::thread::~thread():
0x7fff8c2c9984: pushq %rbp
0x7fff8c2c9985: movq %rsp, %rbp
0x7fff8c2c9988: cmpq $0, (%rdi)
0x7fff8c2c998c: jne 0x7fff8c2c9990 ; std::__1::thread::~thread() +12
0x7fff8c2c998e: popq %rbp
0x7fff8c2c998f: ret
0x7fff8c2c9990: callq 0x7fff8c2ca4fc ; symbol stub for: std::terminate()
0x7fff8c2c9995: nop
仔细看一下,这里怎么会调用thread的析构函数呢?问题就出在这里,直接放一个光溜溜的构造函数,当然会被马上析构了...
改成:
_thread = std::thread( &ConsoleUploadFile::uploadFile, this);
就可以了,_thread为成员变量。
可是,程序退出的时候,又崩溃了,是在析构函数崩溃的
ConsoleUploadFile::~ConsoleUploadFile()
{
}
libc++.1.dylib`std::__1::thread::~thread():
0x7fff8c2c9984: pushq %rbp
0x7fff8c2c9985: movq %rsp, %rbp
0x7fff8c2c9988: cmpq $0, (%rdi)
0x7fff8c2c998c: jne 0x7fff8c2c9990 ; std::__1::thread::~thread() +12
0x7fff8c2c998e: popq %rbp
0x7fff8c2c998f: ret
0x7fff8c2c9990: callq 0x7fff8c2ca4fc ; symbol stub for: std::terminate()
0x7fff8c2c9995: nop
还是和子线程有关,看来是有什么资源没有释放,又是一顿查,原来需要call 一下join(),文档上是这么说的:
After a call to this function, the thread object becomes non-joinable and can be destroyed safely.
ConsoleUploadFile::~ConsoleUploadFile()
{
_thread.join();
}
终于搞定了~