• 一组便于创建线程和线程池的简单封装函数


    /** 
    @file 
    @brief		
    @version	2012-11-08 SammyLan
    */
    
    #pragma once
    #include <memory>
    BEGIN_NAMESPACE(XLANUtil)
    template <typename T>
    class XLANThreadPool
    {
    	typedef std::pair<void (T::*)(), T *> ThreadInfo;
    public:
        static BOOL QueueUserWorkItem(void (T::*function)(void), T *object, ULONG flags = WT_EXECUTELONGFUNCTION)
        {        
            std::auto_ptr<ThreadInfo> p(new ThreadInfo(function, object));
            if (::QueueUserWorkItem(ThreadProc, p.get(), flags))
            {
                //现在由线程函数负责删除前面申请的内存
    			p.release();
                return TRUE;
            }
            else
            {
                return FALSE;
            }
        }
    
    private:
    	static DWORD WINAPI ThreadProc(PVOID context)
        {
    		std::auto_ptr<ThreadInfo> p(static_cast<ThreadInfo *>(context));
            (p->second->*p->first)();
            return 0;
        }
    };
    template <typename T>
    inline BOOL XLANQueueUserWorkItem(T *object,void (T::*function)(void), ULONG flags = WT_EXECUTELONGFUNCTION)
    {
    	return XLANThreadPool<T>::QueueUserWorkItem(function,object,WT_EXECUTELONGFUNCTION);
    }
    
    
    
    template <typename T>
    class XLANThreadObject
    {
    	typedef unsigned int uint;
    	typedef std::pair<void (T::*)(), T *> ThreadInfo;
    public:
    	static HANDLE CreateThread(void (T::*function)(void), T *object)
    	{        
    		std::auto_ptr<ThreadInfo> p(new ThreadInfo(function, object));
    		uint dwTHreadID = 0;
    		HANDLE hThread = (HANDLE)_beginthreadex( NULL, 0, &ThreadProc, p.get(),0,&dwTHreadID);
    		if (hThread != NULL)
    		{
    			//现在由线程函数负责删除前面申请的内存
    			p.release();
    		}
    		return hThread;
    	}
    
    private:
    	static uint WINAPI ThreadProc(PVOID context)
    	{
    		std::auto_ptr<ThreadInfo> p(static_cast<ThreadInfo *>(context));
    		(p->second->*p->first)();
    		return 0;
    	}
    };
    template <typename T>
    inline HANDLE XLANCreateThread(T *object,void (T::*function)(void))
    {
    	return XLANThreadObject<T>::CreateThread(function,object);
    }
    END_NAMESPACE()
    

      例子:

    #include "XLANUtil/XLANThreadPool.h"   
    class MyTest   
    {   
    public:   
     void Test()   
     {   
      XLANUtil::XLANCreateThread(this,&MyTest::Calc);   
      XLANUtil::XLANQueueUserWorkItem(this,&MyTest::Calc);   
     }   
    private:   
     void Calc()   
     {   
     }   
    }; 
    

      

  • 相关阅读:
    第一次个人编程作业
    第一次博客作业
    Put-Me-Down项目Postmortem
    Alpha总结
    git分支与版本管理、版本回退、冲突解决记录
    【Alpha】Daily Scrum Meeting第五次
    【Alpha】Daily Scrum Meeting第四次
    【Alpha】Daily Scrum Meeting第三次
    【Alpha】Daily Scrum Meeting第二次
    一、Daily Scrum Meeting【Alpha】------Clover
  • 原文地址:https://www.cnblogs.com/SammyLan/p/2784218.html
Copyright © 2020-2023  润新知