⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 thread.cpp

📁 串口通信mfc源码
💻 CPP
字号:
// ***************************************************************
//  Thread   version:  1.0   ·  date: 06/30/2006
//  -------------------------------------------------------------
//  
//  -------------------------------------------------------------
//  Copyright (C) 2001-2006 - Midapexsoft All Rights Reserved
// ***************************************************************
// 
// ***************************************************************

#include "stdafx.h"
#include "Thread.h"
#include <process.h>
#include "RuntimeException.h"

// CThread
CThread::CThread()
	:m_hThread(INVALID_HANDLE_VALUE), m_dwId(0)
{
}

CThread::~CThread()
{
	if (m_hThread != INVALID_HANDLE_VALUE)
	{
		::CloseHandle(m_hThread);
		m_hThread = INVALID_HANDLE_VALUE;
	}
}

HANDLE CThread::GetHandle() const
{
	return m_hThread;
}

void CThread::Start()
{
	if ( m_hThread == INVALID_HANDLE_VALUE )
	{
		m_hThread = (HANDLE)::_beginthreadex(0, 0, ThreadFunction, (void*)this, 0,&m_dwId);

		if (m_hThread == INVALID_HANDLE_VALUE)
		{
			THROW_EX_CODE( GetLastError() );
		}
	}
	else
	{
		THROW_EX( _T("Thread already running - you  can't call start once!"));
	}
}

void CThread::Wait() const
{
	if (!Wait(INFINITE))
	{
		THROW_EX( _T("Unexpected timeout on infinite wait"));
	}
}

void CThread::SetPriority(int priority)
{
	if(!::SetThreadPriority(m_hThread, priority))
	{
		THROW_EX_CODE(GetLastError());
	}
}

bool CThread::Wait(DWORD timeoutMillis) const
{
	bool ok;

	DWORD result = ::WaitForSingleObject(m_hThread, timeoutMillis);
	if (result == WAIT_TIMEOUT)
	{
		ok = false;
	}
	else if (result == WAIT_OBJECT_0)
	{
		ok = true;
	}
	else
	{
		THROW_EX_CODE( GetLastError());
	}

	return ok;
}

unsigned int __stdcall CThread::ThreadFunction(void *pV)
{
	int result = 0;

	CThread* pThis = reinterpret_cast<CThread *>(pV);

	if (pThis)
	{
		try
		{
			result = pThis->Run();
		}
		catch(...)
		{
			TRACE(_T("Thread have a uncatch exception.\n"));
		}
	}

	TRACE(_T("Thread exit finished.\n"));
	return result;
}

void CThread::Terminate( DWORD exitCode /* = 0 */)
{
	if(m_hThread != INVALID_HANDLE_VALUE )
	{
		if (!::TerminateThread(m_hThread, exitCode))
		{
			// TODO we could throw an exception here...
		}
	}

	m_hThread = INVALID_HANDLE_VALUE;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -