ThreadPool.hpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #ifndef THREADPOOL_HPP
  2. #define THREADPOOL_HPP
  3. #pragma warning(push)
  4. #pragma warning(disable:4995)
  5. #include <memory>
  6. #pragma warning(pop)
  7. #pragma once
  8. class ThreadPool
  9. {
  10. static const int MAX_THREADS = 50;
  11. template <typename T>
  12. struct ThreadParam
  13. {
  14. void (T::* _function)(); T* _pobject;
  15. ThreadParam(void (T::* function)(), T * pobject)
  16. : _function(function), _pobject(pobject) { }
  17. };
  18. template <typename T>
  19. struct ThreadParamEx
  20. {
  21. void (T::* _function)(ULONG_PTR); T* _pobject; ULONG_PTR _arg;
  22. ThreadParamEx(void (T::* function)(ULONG_PTR), T * pobject, ULONG_PTR arg)
  23. : _function(function), _pobject(pobject), _arg(arg) { }
  24. };
  25. public:
  26. template <typename T>
  27. static bool QueueWorkItem(void (T::*function)(),
  28. T * pobject, ULONG nFlags = WT_EXECUTELONGFUNCTION)
  29. {
  30. std::auto_ptr< ThreadParam<T> > p(new ThreadParam<T>(function, pobject) );
  31. WT_SET_MAX_THREADPOOL_THREADS(nFlags, MAX_THREADS);
  32. bool result = false;
  33. if (::QueueUserWorkItem(WorkerThreadProc<T>,
  34. p.get(),
  35. nFlags))
  36. {
  37. p.release();
  38. result = true;
  39. }
  40. return result;
  41. }
  42. template <typename T>
  43. static bool QueueWorkItem(void (T::*function)(ULONG_PTR),
  44. T * pobject, ULONG_PTR arg, ULONG nFlags = WT_EXECUTELONGFUNCTION)
  45. {
  46. std::auto_ptr< ThreadParamEx<T> > p(new ThreadParamEx<T>(function, pobject, arg) );
  47. WT_SET_MAX_THREADPOOL_THREADS(nFlags, MAX_THREADS);
  48. bool result = false;
  49. if (::QueueUserWorkItem(WorkerThreadProcEx<T>,
  50. p.get(),
  51. nFlags))
  52. {
  53. p.release();
  54. result = true;
  55. }
  56. return result;
  57. }
  58. private:
  59. template <typename T>
  60. static DWORD WINAPI WorkerThreadProc(LPVOID pvParam)
  61. {
  62. std::auto_ptr< ThreadParam<T> > p(static_cast< ThreadParam<T>* >(pvParam));
  63. try {
  64. (p->_pobject->*p->_function)();
  65. }
  66. catch(...) {}
  67. return 0;
  68. }
  69. template <typename T>
  70. static DWORD WINAPI WorkerThreadProcEx(LPVOID pvParam)
  71. {
  72. std::auto_ptr< ThreadParamEx<T> > p(static_cast< ThreadParamEx<T>* >(pvParam));
  73. try {
  74. (p->_pobject->*p->_function)(p->_arg);
  75. }
  76. catch(...) {}
  77. return 0;
  78. }
  79. ThreadPool();
  80. };
  81. #endif //THREADPOOL_HPP