看个例子
class CTimer{
public:
// 析构函数
virtual ~CTimer(){
}
// 开始
void start()
{
b_exit = false;
i = 10;
t = new std::thread(&CTimer::run, this);
}
void run()
{
// Sleep(1000);
// i = 800;
stop();
return;
}
// 结束
void stop()
{
int lll = i;
b_exit = true;
if (t->joinable())
{
t->join();
}
}
private:
std::thread *t;
std::thread *t1;
int i;
bool b_exit;
};
void main(){
CTimer time_test;
time_test.start();
//time_test.stop();
system("pause");
}
如图所示,程序会崩溃,分析了是因为两个线程都在编辑变量t,子线程调用t时主线程不一定赋值已经完成,就会造成空指针的操作,加锁可避免这种问题
附一个别人遇到的问题
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();
}