CSDN博客

img awzzz

任意类成员函数作为线程参数的封装

发表于2004/10/19 17:21:00  633人阅读

// ThreadHelper.h: interface for the ThreadHelper class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_THREADHELPER_H__4A9AE80A_FE7A_4DB3_9D6F_3D1A0C80E314__INCLUDED_)
#define AFX_THREADHELPER_H__4A9AE80A_FE7A_4DB3_9D6F_3D1A0C80E314__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include <windows.h>

//--任意类成员函数作为线程参数的封装
class ThreadIF;  //--封装接口类/在本文最后实现(附使用方法说明)

class ThreadClass {};
template <typename T>
struct ThreadInfo
{
 typedef DWORD (T::*TThreadProc)(void*);
 TThreadProc ThreadProc;
 T* pClass;
 void* pData;
};
typedef ThreadInfo<ThreadClass>::TThreadProc TThreadProc;
class ThreadHelper 
{
public:
 template<typename T>
  void* Start(T* pClass, TThreadProc ThreadProc
  , void* param = 0
  , int* ref = NULL)
 { 
  if (NULL == pClass || NULL == ThreadProc) return NULL;
  
  //--线程计数
  static int count = 1;
  if (_heInfo) count ++;
  if (ref) *ref = count;
  
  ThreadInfo<T>* obj = new ThreadInfo<T>;
  obj->ThreadProc = (ThreadInfo<T>::TThreadProc)ThreadProc;
  obj->pClass = pClass;
  obj->pData = param;

  _heInfo = (ThreadInfo<ThreadClass>*)obj;

  DWORD dwThreadId = 0;
  //--起线程
  HANDLE handle = CreateThread(NULL, 0
   , (LPTHREAD_START_ROUTINE)__ThreadProc
   , _heInfo
   , 0, &dwThreadId);
  return (void*)handle;
 }

public:
 ThreadHelper() : _heInfo(NULL) {};
 virtual ~ThreadHelper() {};

private:
 static DWORD WINAPI __ThreadProc(ThreadInfo<ThreadClass>* obj)
 {
  DWORD ret = (obj->pClass->*(obj->ThreadProc))(obj->pData);
  delete obj;
  return ret;
 };

private:
 ThreadInfo<ThreadClass>* _heInfo;
};

//--Thread interface
class ThreadIF 
{
 virtual DWORD ThreadProc(void* param) { return 0; };
public:
 //--成功返回线程句柄/失败返回0
 inline void* ThreadStart(void* param = 0)
 { return _heThread.Start(this, (TThreadProc)ThreadProc, param, &_count); };
private:
 ThreadHelper _heThread;
 int _count;
public:
 inline int count() { return _count; };//--线程计数
 ThreadIF() : _count (0) {};
};

//class abc{};
//--example
//--把ThreadIF类加为父类
class ThreadIF_ex : public ThreadIF //, abc
{
 //--写一个这样的函数(线程内容)
 //--函数原型不能改变(内容随意)
 virtual DWORD ThreadProc(void* param)
 {
  ::MessageBox(NULL, "ThreadIF_ex", "ThreadHelper+ThreadIF", MB_OK);
  return 0;
 };
};
//--象下面这样就可以启线程了
//ThreadIF_ex a;
//HANDLE handle = a.ThreadStart();
//int count = a.count();

//--参考内容
//http://blog.csdn.net/ringphone/archive/2004/10/18/141074.aspx?Pending=true
//--本文是受以上连接所示内容启发而实现来自己用的接口类

#endif // !defined(AFX_THREADHELPER_H__4A9AE80A_FE7A_4DB3_9D6F_3D1A0C80E314__INCLUDED_)

阅读全文
0 0

相关文章推荐

img
取 消
img