C++スレッドプールの作り方と使い方

C++では、std::threadとstd::vectorを使ってスレッドプールを作成・管理できます。以下に簡単な例を挙げてみます。

#include <iostream>
#include <vector>
#include <thread>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <queue>

class ThreadPool {
public:
    ThreadPool(int numThreads) : stop(false) {
        for (int i = 0; i < numThreads; ++i) {
            workers.emplace_back([this] {
                while (true) {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(queueMutex);
                        condition.wait(lock, [this] { return stop || !tasks.empty(); });
                        if (stop && tasks.empty()) {
                            return;
                        }
                        task = std::move(tasks.front());
                        tasks.pop();
                    }
                    task();
                }
            });
        }
    }

    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            stop = true;
        }
        condition.notify_all();
        for (std::thread& worker : workers) {
            worker.join();
        }
    }

    template<typename F, typename... Args>
    void addTask(F&& f, Args&&... args) {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            tasks.emplace([f=std::forward<F>(f), args=std::make_tuple(std::forward<Args>(args)...)] {
                std::apply(f, args);
            });
        }
        condition.notify_one();
    }

private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;
    std::mutex queueMutex;
    std::condition_variable condition;
    bool stop;
};

// 示例任务函数
void exampleTask(int id) {
    std::cout << "Task " << id << " executed" << std::endl;
}

int main() {
    // 创建线程池并指定线程数量
    ThreadPool pool(4);

    // 添加任务到线程池
    for (int i = 0; i < 8; ++i) {
        pool.addTask(exampleTask, i);
    }

    // 等待所有任务完成
    std::this_thread::sleep_for(std::chrono::seconds(1));

    return 0;
}

上記のサンプルでは、ThreadPoolクラスがスレッドプールの作成と管理のロジックをカプセル化しています。コンストラクタの中で作成するスレッドの数を指定し、それを受けて対応する数のワーカースレッドを作成します。各ワーカースレッドはタスクキューからタスクを取得して実行し、スレッドプールが破棄されるか停止フラグがセットされるまで続けます。

addTask()メソッドは、スレッドプールにタスクを追加するために使用されます。タスクは呼び出し可能なオブジェクトとしてカプセル化され、タスクキューに追加されます。その後、condition.notify_one()を呼び出して、ワーカースレッドにタスクの実行を開始させるよう通知されます。

メイン関数では、ThreadPoolオブジェクトを作成し、addTask()関数でサンプルタスクをいくつか追加します。最後に、std::this_thread::sleep_for()を使用してメインスレッドをスリープさせて、すべてのタスクが終了するのを待ちます。

この例はスレッドプールの作成方法と使い方の説明にのみ使用され、実環境で使用できるスレッドプールの完全な機能や安定性を持たないことに注意してください。実際の使用では、スレッドセーフとエラー処理のメカニズムを考慮する必要があるかもしれません。

bannerAds