1
0

hasync.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. ~GlobalThreadPool() {}
  12. };
  13. /*
  14. * return a future, calling future.get() will wait task done and return RetType.
  15. * async(fn, args...)
  16. * async(std::bind(&Class::mem_fn, &obj))
  17. * async(std::mem_fn(&Class::mem_fn, &obj))
  18. *
  19. */
  20. template<class Fn, class... Args>
  21. auto async(Fn&& fn, Args&&... args) -> std::future<decltype(fn(args...))> {
  22. return GlobalThreadPool::instance()->commit(std::forward<Fn>(fn), std::forward<Args>(args)...);
  23. }
  24. class async {
  25. public:
  26. static void startup(int min_threads = DEFAULT_THREAD_POOL_MIN_THREAD_NUM,
  27. int max_threads = DEFAULT_THREAD_POOL_MAX_THREAD_NUM,
  28. int max_idle_ms = DEFAULT_THREAD_POOL_MAX_IDLE_TIME) {
  29. GlobalThreadPool* gtp = GlobalThreadPool::instance();
  30. if (gtp->isStarted()) return;
  31. gtp->setMinThreadNum(min_threads);
  32. gtp->setMaxThreadNum(max_threads);
  33. gtp->setMaxIdleTime(max_idle_ms);
  34. gtp->start();
  35. }
  36. static void cleanup() {
  37. GlobalThreadPool::exitInstance();
  38. }
  39. };
  40. } // end namespace hv
  41. #endif // HV_ASYNC_H_