Files
cpp-httplib/docs-src/pages/ja/cookbook/s21-thread-pool.md
T
yhirose 9bfd2ddf1c Fix README and docs pages that no longer match the code
Bring the READMEs and the docs pages (en and ja) in line with the
current header:

- Fix the client sample that does not compile, the Transfer-Encoding
  statement for default headers, the verifier callback comment, the
  thread pool spawn rule, the sanitize_filename description, and the
  inverted Accept-Encoding sentence.
- Describe recent behaviour: TLS errors behind Read/Write failures,
  Host validation, Connection: close for a body without length,
  content_reader rules, refused CONNECT, WebSocketClient proxies,
  CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT, the SSE event size limit, and
  the payload limit of the Stream API.
- Complete the API references of WebSocket, WebSocketClient and the
  stream:: helpers, and the SSE reconnect rules.
- Fix cookbook pages: keychain loading on every backend, received Close
  status, a multipart sample that trusted the client's file name, an
  echo sample that sent binary as text, SNI, pre-request handler scope,
  stop() with WebSocket handlers, and the thread pool notes.
- Restore the mutex in the LLM app's Chapter 5 code.
2026-10-18 10:13:57 -04:00

70 lines
2.8 KiB
Markdown

---
title: "S21. マルチスレッド数を設定する"
order: 40
status: "draft"
---
cpp-httplibは、リクエストをスレッドプールで並行処理します。デフォルトでは`std::thread::hardware_concurrency() - 1`と`8`のうち大きいほうがベーススレッド数で、負荷に応じてその4倍まで動的にスケールします。スレッド数を明示的に調整したいときは、`new_task_queue`に自分でファクトリを設定します。
## スレッド数を指定する
```cpp
httplib::Server svr;
svr.new_task_queue = [] {
return new httplib::ThreadPool(/*base_threads=*/8, /*max_threads=*/64);
};
svr.listen("0.0.0.0", 8080);
```
ファクトリは`TaskQueue*`を返すラムダです。`ThreadPool`にベーススレッド数と最大スレッド数を渡すと、負荷に応じて間のスレッド数が自動で増減します。アイドルになったスレッドは一定時間(デフォルトは3秒)で終了します。
## キューの上限も指定する
キューが溜まりすぎるとメモリを食うので、キューの最大長も指定できます。
```cpp
svr.new_task_queue = [] {
return new httplib::ThreadPool(
/*base_threads=*/12,
/*max_threads=*/0, // 動的スケーリング無効
/*max_queued_requests=*/18);
};
```
`max_threads=0`にすると動的スケーリングが無効になり、固定の`base_threads`だけで処理します。`max_queued_requests`を超えるとリクエストが拒否されます。
## 独自のスレッドプールを使う
自前のスレッドプール実装を差し込むこともできます。`TaskQueue`を継承したクラスを作り、ファクトリから返します。
```cpp
class MyTaskQueue : public httplib::TaskQueue {
public:
MyTaskQueue(size_t n) { pool_.start_with_thread_count(n); }
bool enqueue(std::function<void()> fn) override { return pool_.post(std::move(fn)); }
void shutdown() override { pool_.shutdown(); }
private:
MyThreadPool pool_;
};
svr.new_task_queue = [] { return new MyTaskQueue(12); };
```
既存のスレッドプールライブラリがあるなら、そちらに委譲できるので、プロジェクト内でスレッド管理を統一したいときに便利です。
## ビルド時の調整
コンパイル時に変更したい場合は、マクロで初期値を設定できます。
```cpp
#define CPPHTTPLIB_THREAD_POOL_COUNT 16 // ベーススレッド数
#define CPPHTTPLIB_THREAD_POOL_MAX_COUNT 128 // 最大スレッド数
#define CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT 5 // アイドル終了までの秒数
#include <httplib.h>
```
> **Note:** WebSocket接続はその生存期間中ずっと1スレッドを占有します。大量の同時WebSocket接続を扱うなら、最大スレッド数を引き上げておきましょう(`ThreadPool(8, 64)`のように)。