ATL 线程池的使用
生活随笔
收集整理的這篇文章主要介紹了
ATL 线程池的使用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?
一.自定義一個Worker
class CMyWorker{public:typedef MyRequestType RequestType;BOOL Initialize(void* pvWorkerParam);void Execute(MyRequestType request, void* pvWorkerParam, OVERLAPPED* pOverlapped);void Terminate(void* pvWorkerParam);};必須實現(xiàn)以上接口
具體參考如下:
http://msdn.microsoft.com/zh-cn/library/ytkt93h8.aspx
Demo:
LONG g_lCurrId = -1;class CMyWorker { public:typedef DWORD_PTR RequestType;CMyWorker() : m_dwExecs( 0 ){m_lId = InterlockedIncrement( &g_lCurrId );}virtual BOOL Initialize(void *pvParam){printf("[%d]: CMyWorker.Initialize(%d)\n", (DWORD_PTR)::GetCurrentThreadId(), (DWORD_PTR)pvParam );return TRUE;}virtual void Terminate(void* /*pvParam*/){printf( "CMyWorker #%d exec'd %d times.\n", m_lId, m_dwExecs );}void Execute(RequestType dw, void *pvParam, OVERLAPPED* pOverlapped) throw(){ATLASSERT(pvParam != NULL);printf("[%d] CMyWorker::Execute(dw=%d, pvParam=%d, pOverlapped=%d\n", ::GetCurrentThreadId(), dw, (DWORD_PTR)pvParam, (DWORD_PTR)pOverlapped);CTaskBase* pTask = (CTaskBase*)(DWORD_PTR)dw;pTask->DoTask(pvParam, pOverlapped);m_dwExecs++;}virtual BOOL GetWorkerData(DWORD /*dwParam*/, void ** /*ppvData*/){return FALSE;}protected:DWORD m_dwExecs;LONG m_lId; }; // CMyWorker二.線程池(CThreadPool)
#define THREADPOOL_SIZE 5/// int main(int /*argc*/, char* /*argv[]*/) {CThreadPool<CMyWorker> pool;CTaskArray tasks;HRESULT hr = pool.Initialize((void*)321, THREADPOOL_SIZE);if( SUCCEEDED( hr ) ) {int i = -1;CTaskBase* pTask = NULL;if ( CreateTasks(tasks, 100) ) {for ( i = 0; i < tasks.GetSize(); i++ ) {pTask = tasks[ i ];ATLASSERT( NULL != pTask );pool.QueueRequest( (CMyWorker::RequestType) pTask );}}// Allow a little time for all the tasks to completeSleep(1000);// Clean up the tasks and shutdown the thread poolfor ( i = 0; i < tasks.GetSize(); i++ ) {pTask = tasks[ i ];ATLASSERT( NULL != pTask );delete pTask;}// Shutdown the thread poolpool.Shutdown();}elseprintf("Failed to init thread pool!");printf("\n");return 0; }參考:http://msdn.microsoft.com/zh-cn/library/dta23y51.aspx
三.IThreadPoolConfig
定義了一個基礎的接口
// Used to configure the worker thread pool. This can be used by any // client of the CThreadPool class. __interface __declspec(uuid("B1F64757-6E88-4fa2-8886-7848B0D7E660"))IThreadPoolConfig : public IUnknown {STDMETHOD(SetSize)(_In_ int nNumThreads);STDMETHOD(GetSize)(_Out_ int *pnNumThreads);STDMETHOD(SetTimeout)(_In_ DWORD dwMaxWait);STDMETHOD(GetTimeout)(_Out_ DWORD *pdwMaxWait); };四.ThreadTraits
分兩種CRTThreadTraits和Win32ThreadTraits,分別調用_beginthreadex和CreateThread方法
五.WaitTraits
只實現(xiàn)了Win32WaitTraits了,即調用了WaitForSingleObject
轉載于:https://www.cnblogs.com/Clingingboy/archive/2011/07/16/2108391.html
總結
以上是生活随笔為你收集整理的ATL 线程池的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS开发那些事-iOS常用设计模式–委
- 下一篇: [转载]Tomcat 6.0 安装配置