c++ thread 使用不当导致的崩溃问题

本文探讨了在C++中使用std::thread时遇到的线程安全问题,特别是析构函数导致的崩溃现象。通过具体代码示例,分析了在构造函数和析构函数中直接操作线程可能引发的问题,并提供了正确的线程管理和资源释放方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看个例子

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();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值