|
| 1 | +--- |
| 2 | +title: ThreadPoolFs |
| 3 | +description: Thread Pool for Blocking Filesystem Operations |
| 4 | +--- |
| 5 | + |
| 6 | +Operating systems contain many blocking operations. To handle these efficiently, ManapiHttp provides the ThreadPoolFs method, which sets up a thread pool specifically for blocking operations (particularly filesystem operations). Users can also add their own tasks to ThreadPoolFs. Note that ThreadPoolFs cannot be modified while the event loop is running. |
| 7 | + |
| 8 | +<Callout title="Information">The default size for ThreadPoolFs is 4 threads.</Callout> |
| 9 | + |
| 10 | +### Initialize ThreadPoolFs |
| 11 | +```cpp |
| 12 | +#include <manapihttp/std/ManapiAsyncContext.hpp> |
| 13 | + |
| 14 | +int main(int argc, char *argv[]) { |
| 15 | + /* Configures event loops to use 2 threads for blocking I/O system calls */ |
| 16 | + manapi::async::context::threadpoolfs(2); |
| 17 | + |
| 18 | + return 0; |
| 19 | +} |
| 20 | +``` |
| 21 | +
|
| 22 | +### Create a Task |
| 23 | +```cpp |
| 24 | +#include <chrono> |
| 25 | +#include <thread> |
| 26 | +
|
| 27 | +#include <manapihttp/ManapiDebug.hpp> |
| 28 | +#include <manapihttp/ManapiEventLoop.hpp> |
| 29 | +#include <manapihttp/std/ManapiAsyncContext.hpp> |
| 30 | +
|
| 31 | +int main(int argc, char *argv[]) { |
| 32 | + manapi::async::context::threadpoolfs(2); |
| 33 | + auto ctx = manapi::async::context::create().unwrap(); |
| 34 | +
|
| 35 | + ctx->run([](std::function<void()> bind) -> void { |
| 36 | + manapi::async::current()->eventloop()->append_task([](const manapi::ev::shared_work &w) -> void { |
| 37 | + // This executes in a worker thread |
| 38 | + assert(!manapi::async::context_exists()); |
| 39 | +
|
| 40 | + std::chrono::seconds duration(5); |
| 41 | + std::this_thread::sleep_for(duration); |
| 42 | +
|
| 43 | + manapi_log_debug("Waiting has finished"); |
| 44 | + }, [](const manapi::ev::shared_work &w, int status) -> void { |
| 45 | + // This executes back in the main event loop thread |
| 46 | + assert(manapi::async::context_exists()); |
| 47 | + |
| 48 | + manapi_log_debug("Waiting has finished with status: %d", status); |
| 49 | +
|
| 50 | + // Stop the event loop |
| 51 | + manapi::async::run(manapi::async::current()->eventloop()->stop()); |
| 52 | + }); |
| 53 | +
|
| 54 | + manapi_log_debug("Waiting has started"); |
| 55 | +
|
| 56 | + bind(); |
| 57 | + }); |
| 58 | +
|
| 59 | + return 0; |
| 60 | +} |
| 61 | +``` |
0 commit comments