1+ // GlobalThreadPool.h
2+ #pragma once
3+
4+ #include " HighPerformanceThreadPool.h"
5+ #include < memory>
6+ #include < mutex>
7+
8+ class GlobalThreadPool {
9+ private:
10+ inline static std::unique_ptr<HighPerformanceThreadPool> instance;
11+ inline static std::once_flag initFlag;
12+
13+ GlobalThreadPool () = delete ;
14+
15+ public:
16+ // Initialize the global thread pool (call once at app startup)
17+ static void initialize (size_t numThreads = 0 , ThreadConfig config = {}) {
18+ std::call_once (initFlag, [&numThreads, config]() {
19+ // Auto-detect optimal thread count if not specified
20+ if (numThreads == 0 ) {
21+ numThreads = std::thread::hardware_concurrency ();
22+ numThreads = std::min (numThreads, size_t (4 )); // Cap at 4 for mobile
23+ }
24+
25+ LOGI (" Initializing global thread pool with %zu threads" , numThreads);
26+ instance =
27+ std::make_unique<HighPerformanceThreadPool>(numThreads, config);
28+ });
29+ }
30+
31+ // Get the global thread pool instance
32+ static HighPerformanceThreadPool &get () {
33+ if (!instance) {
34+ // Auto-initialize with defaults if not already initialized
35+ initialize ();
36+ }
37+ return *instance;
38+ }
39+
40+ // Convenience methods that mirror std::thread interface
41+ template <typename Func, typename ... Args>
42+ static auto async (Func &&func, Args &&...args) {
43+ return get ().submit (std::forward<Func>(func), std::forward<Args>(args)...);
44+ }
45+
46+ template <typename Func, typename ... Args>
47+ static auto async_high_priority (Func &&func, Args &&...args) {
48+ return get ().submitWithPriority (Priority::HIGH, std::forward<Func>(func),
49+ std::forward<Args>(args)...);
50+ }
51+
52+ // Fire and forget (like std::thread{}.detach())
53+ template <typename Func, typename ... Args>
54+ static void detach (Func &&func, Args &&...args) {
55+ get ().submitDetached (std::forward<Func>(func), std::forward<Args>(args)...);
56+ }
57+
58+ // Execute and wait (like std::thread{}.join())
59+ template <typename Func, typename ... Args>
60+ static auto execute (Func &&func, Args &&...args) {
61+ return get ().execute (std::forward<Func>(func), std::forward<Args>(args)...);
62+ }
63+
64+ static void shutdown () {
65+ if (instance) {
66+ instance->shutdown ();
67+ instance.reset ();
68+ }
69+ }
70+ };
71+
72+ // Static member definitions
73+ // std::unique_ptr<HighPerformanceThreadPool> GlobalThreadPool::instance;
74+ // std::once_flag GlobalThreadPool::initFlag;
75+
76+ // Convenience macros for even simpler usage
77+ #define ASYNC_TASK (...) GlobalThreadPool::async(__VA_ARGS__)
78+ #define ASYNC_HIGH (...) GlobalThreadPool::async_high_priority(__VA_ARGS__)
79+ #define ASYNC_DETACH (...) GlobalThreadPool::detach(__VA_ARGS__)
80+ #define ASYNC_WAIT (...) GlobalThreadPool::execute(__VA_ARGS__)
0 commit comments