hasync.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #ifndef HV_ASYNC_H_
  2. #define HV_ASYNC_H_
  3. #include "hexport.h"
  4. #include "hthreadpool.h"
  5. #include "singleton.h"
  6. namespace hv {
  7. class HV_EXPORT GlobalThreadPool : public HThreadPool {
  8. SINGLETON_DECL(GlobalThreadPool)
  9. protected:
  10. GlobalThreadPool() : HThreadPool() {}
  11. };
  12. /*
  13. * return a future, calling future.get() will wait task done and return RetType.
  14. * async(fn, args...)
  15. * async(std::bind(&Class::mem_fn, &obj))
  16. * async(std::mem_fn(&Class::mem_fn, &obj))
  17. *
  18. */
  19. template<class Fn, class... Args>
  20. auto async(Fn&& fn, Args&&... args) -> std::future<decltype(fn(args...))> {
  21. return GlobalThreadPool::instance()->commit(std::forward<Fn>(fn), std::forward<Args>(args)...);
  22. }
  23. class async {
  24. public:
  25. static void startup(int min_threads = DEFAULT_THREAD_POOL_MIN_THREAD_NUM,
  26. int max_threads = DEFAULT_THREAD_POOL_MAX_THREAD_NUM,
  27. int max_idle_ms = DEFAULT_THREAD_POOL_MAX_IDLE_TIME) {
  28. GlobalThreadPool* gtp = GlobalThreadPool::instance();
  29. if (gtp->isStarted()) return;
  30. gtp->setMinThreadNum(min_threads);
  31. gtp->setMaxThreadNum(max_threads);
  32. gtp->setMaxIdleTime(max_idle_ms);
  33. gtp->start();
  34. }
  35. static void cleanup() {
  36. GlobalThreadPool::exitInstance();
  37. }
  38. };
  39. } // end namespace hv
  40. #endif // HV_ASYNC_H_