编程语言
首页 > 编程语言> > C++ 线程类析构死锁问题

C++ 线程类析构死锁问题

作者:互联网

文章目录

一、前言

二、引例

1、案例描述

2、案例实现

#include "Thread.h"


class LogicThread : public Thread
{
public:
	LogicThread() : m_bStop(false) {
	}
protected:
	virtual void DoWork() {
		while (!m_bStop) {
			printf("Thread[%d]: I'm active!\n", GetId());
			Sleep(16);
		}
		printf("Thread[%d]: I'm exit!\n", GetId());
	}

private:
	bool                      m_bStop;
};

int main() {
	LogicThread *pLS = new LogicThread;
	pLS->Start();
	Sleep(500);
	delete pLS;
	return 0;
}

三、问题分析

一、输出

Thread[70508]: I'm active!
Thread[70508]: I'm active!
Thread[70508]: I'm active!
Thread[70508]: I'm active!
Thread[70508]: I'm active!
Thread[70508]: I'm active!
...

二、分析

Thread::~Thread() {
	Stop();
}

void Thread::Stop() {
	if (!m_pkHandle) {
		return;
	}
	WaitForSingleObject((HANDLE)m_pkHandle, INFINITE);
	CloseHandle((HANDLE)m_pkHandle);
	m_pkHandle = NULL;
}

四、改进方案

#include "Thread.h"


class LogicThread : public Thread
{
public:
	LogicThread() : m_bStop(false) {
	}
protected:
	virtual void DoWork() {
		int nCnt = 100;
		while (!m_bStop) {
			printf("Thread[%d]: I'm active!\n", GetId());
			Sleep(16);
			if (--nCnt == 0) {
				m_bStop = true;  // 增加结束条件
			}
		}
		printf("Thread[%d]: I'm exit!\n", GetId());
	}
private:
	bool                      m_bStop;
};

int main() {
	LogicThread *pLS = new LogicThread;
	pLS->Start();
	// 主线程等待子线程退出;
	do {
		Sleep(16);
	} while (pLS->IsRunning());
	// 清理线程信息
	delete pLS;
	return 0;
}

标签:类析构,Thread,死锁,线程,active,pLS,LogicThread,bStop
来源: https://blog.51cto.com/u_15239535/2836978