### ThreadPool::start(int size) Source: https://context7.com/codesingeralex/threadpoolutil/llms.txt Initializes and starts the thread pool with a specified number of worker threads. ```APIDOC ## void ThreadPool::start(int size) ### Description Starts the thread pool and creates the specified number of worker threads. The pool begins accepting tasks only after this method is called. ### Method Method Call ### Parameters #### Path Parameters - **size** (int) - Required - The number of worker threads to create. ``` -------------------------------- ### Start ThreadPool Workers Source: https://context7.com/codesingeralex/threadpoolutil/llms.txt Initializes the thread pool with a specified number of worker threads. The pool must be started before it can accept tasks. ```cpp #include "threadpool.hpp" int main() { ThreadPool pool; // 启动线程池,创建 4 个工作线程 pool.start(4); // 启动线程池,创建 8 个工作线程 // pool.start(8); // 线程池现在可以接收任务 return 0; } ``` -------------------------------- ### Configure ThreadPool Mode Source: https://context7.com/codesingeralex/threadpoolutil/llms.txt Sets the operating mode to either MODE_FIXED or MODE_CACHED. This configuration must be applied before calling start(). ```cpp #include "threadpool.hpp" int main() { ThreadPool pool; // 设置为动态缓存模式 // MODE_CACHED: 根据任务负载动态创建/回收线程 pool.setMode(PoolMode::MODE_CACHED); // 或使用固定模式(默认) // pool.setMode(PoolMode::MODE_FIXED); pool.start(4); return 0; } ``` -------------------------------- ### ThreadPool::setMode(PoolMode mode) Source: https://context7.com/codesingeralex/threadpoolutil/llms.txt Configures the operating mode of the thread pool. Must be called before start(). ```APIDOC ## void ThreadPool::setMode(PoolMode mode) ### Description Sets the working mode of the thread pool. Options are MODE_FIXED (fixed thread count) or MODE_CACHED (dynamic thread creation/recycling). ### Method Method Call ### Parameters #### Path Parameters - **mode** (PoolMode) - Required - The mode to set (MODE_FIXED or MODE_CACHED). ``` -------------------------------- ### Block and Wait for Task Completion Source: https://context7.com/codesingeralex/threadpoolutil/llms.txt The get() method blocks the calling thread until the task completes. If the task fails or times out, it returns an empty result. ```cpp #include "threadpool.hpp" #include class SlowTask : public Task { public: Any run() override { // 模拟耗时操作 this_thread::sleep_for(chrono::seconds(2)); return string("Task completed"); } }; int main() { ThreadPool pool; pool.start(2); Result result = pool.submitTask(make_shared()); cout << "Waiting for result..." << endl; // get() 会阻塞直到任务完成 Any any = result.get(); string value = any.cast_(); cout << "Result: " << value << endl; return 0; } ``` -------------------------------- ### Compile ThreadPoolUtil Projects Source: https://github.com/codesingeralex/threadpoolutil/blob/main/README.md Use the g++ compiler with C++20 support and the -pthread flag to build the application. ```shell g++ -std=c++2a test.cpp threadpool.cpp -o test -pthread ``` -------------------------------- ### Define and Execute Tasks with ThreadPoolUtil Source: https://github.com/codesingeralex/threadpoolutil/blob/main/README.md Implement a custom task by inheriting from the Task base class and use the ThreadPool to submit tasks and retrieve results. ```cpp # include "threadpool.hpp" /* * 创建一个类继承Task基类并重写run方法 */ class MyTask : public Task{ public: /* * 可以自定义MyTask的构造函数 */ MyTask(int begin, int end) : begin_(begin), end_(end) {} Any run() { int sum; for(int i = begin_; i < end_; i++) { sum += i; } return sum; } private: int begin_; int end_; } int main() { /* * 创建线程池 */ ThreadPool pool; /* * 启动线程池时可以自定义线程数量 */ pool.start(4); /* * Result::submitTask(shared_ptr()); * 使用Result接收任意类型返回值 */ Result res1 = pool.submitTask(make_shared(0, 16384)); Result res2 = pool.submitTask(make_shared(16385, 32768)); Result res2 = pool.submitTask(make_shared(32769, 49152)); Result res2 = pool.submitTask(make_shared(49153, 65535)); /* * 使用Result::get().cast_()进行类型转换 */ int result = res1.get().cast_() + res2.get().cast_() + res3.get().cast_() + res4.get().cast_(); } ``` -------------------------------- ### Parallel computation using ThreadPool Source: https://context7.com/codesingeralex/threadpoolutil/llms.txt Shows a complete workflow for configuring the thread pool, defining a task, submitting multiple tasks, and aggregating results. ```cpp #include "threadpool.hpp" #include #include #include // 计算区间和的任务 class RangeSumTask : public Task { public: RangeSumTask(int start, int end) : start_(start), end_(end) {} Any run() override { long long sum = 0; for (int i = start_; i <= end_; i++) { sum += i; } return sum; } private: int start_; int end_; }; int main() { // 创建并配置线程池 ThreadPool pool; pool.setMode(PoolMode::MODE_CACHED); // 动态模式 pool.setTaskCapacity(100); // 任务队列容量 pool.setThreadCapacity(8); // 最大线程数 pool.start(4); // 初始 4 个线程 auto startTime = chrono::high_resolution_clock::now(); // 将 1-1000000 的求和分成 4 个子任务 vector results; results.push_back(pool.submitTask(make_shared(1, 250000))); results.push_back(pool.submitTask(make_shared(250001, 500000))); results.push_back(pool.submitTask(make_shared(500001, 750000))); results.push_back(pool.submitTask(make_shared(750001, 1000000))); // 收集所有结果 long long totalSum = 0; for (auto& res : results) { totalSum += res.get().cast_(); } auto endTime = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast(endTime - startTime); cout << "Sum of 1 to 1000000: " << totalSum << endl; cout << "Time elapsed: " << duration.count() << " ms" << endl; // 预期输出: // Sum of 1 to 1000000: 500000500000 // Time elapsed: ~XX ms return 0; } // 编译命令: // g++ -std=c++2a main.cpp threadpool.cpp -o main -pthread ``` -------------------------------- ### Initialize ThreadPool Instance Source: https://context7.com/codesingeralex/threadpoolutil/llms.txt Creates a default ThreadPool instance configured with MODE_FIXED, a task queue capacity of 1024, and a maximum of 10 threads. ```cpp #include "threadpool.hpp" int main() { // 创建线程池实例 ThreadPool pool; // 线程池默认配置: // - 模式:MODE_FIXED(固定线程数) // - 任务队列容量:1024 // - 线程最大数量:10 return 0; } ``` -------------------------------- ### Implement Custom Task Classes Source: https://context7.com/codesingeralex/threadpoolutil/llms.txt Inherit from the Task base class and implement the run() method to return any type wrapped in an Any container. ```cpp #include "threadpool.hpp" #include #include // 返回整数的任务 class IntTask : public Task { public: Any run() override { return 42; } }; // 返回字符串的任务 class StringTask : public Task { public: StringTask(const string& msg) : message_(msg) {} Any run() override { return string("Processed: ") + message_; } private: string message_; }; // 返回复杂对象的任务 struct ResultData { int code; string message; }; class ComplexTask : public Task { public: Any run() override { ResultData data{200, "Success"}; return data; } }; int main() { ThreadPool pool; pool.start(4); // 提交不同类型返回值的任务 Result r1 = pool.submitTask(make_shared()); Result r2 = pool.submitTask(make_shared("Hello")); Result r3 = pool.submitTask(make_shared()); // 使用 cast_() 获取对应类型的结果 int num = r1.get().cast_(); string str = r2.get().cast_(); ResultData data = r3.get().cast_(); cout << "Int result: " << num << endl; cout << "String result: " << str << endl; cout << "Complex result: " << data.code << " - " << data.message << endl; return 0; } ``` -------------------------------- ### Convert Any container values with cast_() Source: https://context7.com/codesingeralex/threadpoolutil/llms.txt Demonstrates converting task results to specific types using cast_(). Throws an exception if the requested type does not match the stored value. ```cpp #include "threadpool.hpp" #include class MultiTypeTask : public Task { public: MultiTypeTask(int type) : type_(type) {} Any run() override { switch (type_) { case 1: return 100; case 2: return 3.14159; case 3: return string("Hello World"); default: return 0; } } private: int type_; }; int main() { ThreadPool pool; pool.start(4); Result r1 = pool.submitTask(make_shared(1)); Result r2 = pool.submitTask(make_shared(2)); Result r3 = pool.submitTask(make_shared(3)); // 正确的类型转换 int intVal = r1.get().cast_(); double doubleVal = r2.get().cast_(); string strVal = r3.get().cast_(); cout << "Int: " << intVal << endl; cout << "Double: " << doubleVal << endl; cout << "String: " << strVal << endl; // 错误的类型转换会抛出异常 // int wrong = r3.get().cast_(); // throws "type is unmatch!" return 0; } ``` -------------------------------- ### Submit Tasks and Retrieve Results Source: https://context7.com/codesingeralex/threadpoolutil/llms.txt Submits a task to the pool and retrieves a Result object. Use cast_() on the result to extract the return value. ```cpp #include "threadpool.hpp" #include #include // 定义自定义任务类 class SumTask : public Task { public: SumTask(int begin, int end) : begin_(begin), end_(end) {} Any run() override { long long sum = 0; for (int i = begin_; i <= end_; i++) { sum += i; } return sum; // 返回任意类型 } private: int begin_; int end_; }; int main() { ThreadPool pool; pool.start(4); // 提交任务并获取 Result 对象 Result res1 = pool.submitTask(make_shared(1, 100000)); Result res2 = pool.submitTask(make_shared(100001, 200000)); // 获取结果(阻塞等待) long long sum1 = res1.get().cast_(); long long sum2 = res2.get().cast_(); cout << "Sum 1-100000: " << sum1 << endl; cout << "Sum 100001-200000: " << sum2 << endl; cout << "Total: " << sum1 + sum2 << endl; return 0; } ``` -------------------------------- ### Set Task Queue Capacity Source: https://context7.com/codesingeralex/threadpoolutil/llms.txt Defines the maximum number of tasks the queue can hold. Exceeding this capacity will cause new submissions to wait or timeout. ```cpp #include "threadpool.hpp" int main() { ThreadPool pool; // 设置任务队列最大容量为 2048 pool.setTaskCapacity(2048); pool.start(4); return 0; } ``` -------------------------------- ### Result::get() Source: https://context7.com/codesingeralex/threadpoolutil/llms.txt Retrieves the result of a submitted task, blocking until completion. ```APIDOC ## Any Result::get() ### Description Blocks the calling thread until the associated task completes, then returns the result as an Any type. Use .cast_() to convert the result to the desired type. ### Method Method Call ### Response #### Success Response - **Any** (Object) - The result of the task execution. ``` -------------------------------- ### ThreadPool::submitTask(shared_ptr task) Source: https://context7.com/codesingeralex/threadpoolutil/llms.txt Submits a task to the thread pool for execution and returns a Result object. ```APIDOC ## Result ThreadPool::submitTask(shared_ptr task) ### Description Submits a task to the thread pool. The method has a 1-second timeout for submission. Returns a Result object used to retrieve the task's return value. ### Method Method Call ### Parameters #### Path Parameters - **task** (shared_ptr) - Required - A shared pointer to a class inheriting from the Task base class. ### Response #### Success Response - **Result** (Object) - A wrapper object containing the task execution result. ``` -------------------------------- ### Set Maximum Thread Capacity Source: https://context7.com/codesingeralex/threadpoolutil/llms.txt Limits the number of threads in MODE_CACHED. This setting is ignored in MODE_FIXED. ```cpp #include "threadpool.hpp" int main() { ThreadPool pool; // 设置动态模式 pool.setMode(PoolMode::MODE_CACHED); // 设置最大线程数为 20 pool.setThreadCapacity(20); pool.start(4); // 初始 4 个线程,最多扩展到 20 个 return 0; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.