1#ifndef CPR_ASYNC_H
2#define CPR_ASYNC_H
3
4#include "async_wrapper.h"
5#include "singleton.h"
6#include "threadpool.h"
7
8namespace cpr {
9
10class GlobalThreadPool : public ThreadPool {
11 CPR_SINGLETON_DECL(GlobalThreadPool)
12 protected:
13 GlobalThreadPool() = default;
14
15 public:
16 ~GlobalThreadPool() override = default;
17};
18
19/**
20 * Return a wrapper for a future, calling future.get() will wait until the task is done and return RetType.
21 * async(fn, args...)
22 * async(std::bind(&Class::mem_fn, &obj))
23 * async(std::mem_fn(&Class::mem_fn, &obj))
24 **/
25template <class Fn, class... Args>
26auto async(Fn&& fn, Args&&... args) {
27 return AsyncWrapper{GlobalThreadPool::GetInstance()->Submit(std::forward<Fn>(fn), std::forward<Args>(args)...)};
28}
29
30class async {
31 public:
32 static void startup(size_t min_threads = CPR_DEFAULT_THREAD_POOL_MIN_THREAD_NUM, size_t max_threads = CPR_DEFAULT_THREAD_POOL_MAX_THREAD_NUM, std::chrono::milliseconds max_idle_ms = CPR_DEFAULT_THREAD_POOL_MAX_IDLE_TIME) {
33 GlobalThreadPool* gtp = GlobalThreadPool::GetInstance();
34 if (gtp->IsStarted()) {
35 return;
36 }
37 gtp->SetMinThreadNum(min_threads);
38 gtp->SetMaxThreadNum(max_threads);
39 gtp->SetMaxIdleTime(max_idle_ms);
40 gtp->Start();
41 }
42
43 static void cleanup() {
44 GlobalThreadPool::ExitInstance();
45 }
46};
47
48} // namespace cpr
49
50#endif
51