线程消息队列

线程消息队列的使用场景

工作者线程用于处理一个操作,立即返回实现异步;线程消息队列可以用来处理一组操作,可以实现一组操作异步,且多个异步操作可以共享状态。

#ifndef _ROVERLIB_MAINTHREAD_H_
#define _ROVERLIB_MAINTHREAD_H_

#include <atlsync.h>

using namespace ATL;

class CMainThread
{
protected:
	CMainThread();
	virtual ~CMainThread();

	BOOL InitInstance();
	DWORD ExitInstance();
	DWORD Run();
	
public:
	virtual int OnThreadMessage(UINT Msg, WPARAM wParam, LPARAM lParam);
	static CMainThread* Create(int nPriority = THREAD_PRIORITY_NORMAL, DWORD dwCreateFlags = 0);
	static DWORD WINAPI ThreadProc(LPVOID lpParameter);


	void Quit();
	DWORD SuspendThread();
	DWORD ResumeThread();
	
	

public:
	ATL::CCriticalSection m_CriticalSection;
	ATL::CEvent m_EventStarted;
	DWORD m_dwThreadId;
	HANDLE m_hThread;
	unsigned int m_nInternalMessageID;
private:
	BOOL PostThreadMessage(UINT message , WPARAM wParam, LPARAM lParam);

};

CMainThread* CMainThread::Create( int nPriority /*= THREAD_PRIORITY_NORMAL*/, DWORD dwCreateFlags /*= 0*/ )
{
	CMainThread* pMainThread = new CMainThread();
	pMainThread->m_hThread=CreateThread(0, 0, ThreadProc, pMainThread, dwCreateFlags, &pMainThread->m_dwThreadId);
	if (!pMainThread->m_hThread)
	{
		delete pMainThread;
		return NULL;
	}
	::SetThreadPriority(pMainThread->m_hThread, nPriority);
}

DWORD WINAPI CMainThread::ThreadProc( LPVOID lpParameter )
{
	return ((CMainThread *)lpParameter)->Run();
}

DWORD CMainThread::Run()
{
	m_CriticalSection.Enter();
	InitInstance();
	m_CriticalSection.Leave();

	MSG msg;
	while (GetMessage(&msg, 0, 0, 0))
	{
		TranslateMessage(&msg);
		if (!msg.hwnd)
			OnThreadMessage(msg.message, msg.wParam, msg.lParam);
		DispatchMessage(&msg);
	}
	DWORD res = ExitInstance();
	delete this;
	return res;
}

DWORD CMainThread::SuspendThread()
{

}

DWORD CMainThread::ResumeThread()
{
	BOOL res=::ResumeThread(m_hThread);
	if (res)
	{
		//m_EventStarted.Lock();
		//m_EventStarted.Unlock();
	}
	return res;
}

CMainThread::CMainThread()
{
	m_hThread = 0;
	m_dwThreadId = 0;
}

CMainThread::~CMainThread()
{
	CloseHandle(m_hThread);
}

BOOL CMainThread::InitInstance()
{
	return TRUE;
}

DWORD CMainThread::ExitInstance()
{
	return 1;
}

BOOL CMainThread::PostThreadMessage( UINT message , WPARAM wParam, LPARAM lParam )
{
	return ::PostThreadMessage(m_dwThreadId, message, wParam, lParam);
}

int CMainThread::OnThreadMessage( UINT Msg, WPARAM wParam, LPARAM lParam )
{
	if (Msg == m_nInternalMessageID)
	{		
		return TRUE;
	}

	return TRUE;
}





#endif

用法

m_nInternalMessageID = RegisterWindowMessage(_T("Message{F958620E-040C-4b33-A091-7E04E10AA660}"));


if (!m_nInternalMessageID)
    return FZ_REPLY_NOTINITIALIZED;


//Create thread object
m_pMainThread = CMainThread::Create(THREAD_PRIORITY_BELOW_NORMAL, CREATE_SUSPENDED);


//Initialize Thread variables
m_pMainThread->m_nInternalMessageID = m_nInternalMessageID;
m_pMainThread->m_nReplyMessageID = m_nReplyMessageID;
m_pMainThread->m_hOwnerWnd = m_hOwnerWnd;


//Resume Thread
m_pMainThread->ResumeThread();

你可能感兴趣的:(线程消息队列)