[c++] C++ 스레드 풀의 동작 원리

C++ 스레드 풀은 여러 가지 작업을 처리하기 위해 여러 스레드를 재사용하는 메커니즘입니다. 스레드 풀은 대부분의 멀티스레드 애플리케이션에서 성능을 향상시키는 데 사용됩니다.

동작 원리

  1. 스레드 생성: 초기화 과정에서 스레드 풀은 필요한 수의 스레드를 생성하거나 미리 생성된 스레드를 관리합니다.
  2. 작업 큐: 스레드 풀은 작업을 저장하는 큐를 유지합니다. 이 큐에는 처리해야 할 작업들이 대기하고 있습니다.
  3. 작업 할당: 작업이 새로 추가되면 스레드 풀은 이를 작업 큐에 넣습니다. 미리 생성된 스레드는 작업 큐에서 작업을 가져와 실행합니다.
  4. 작업 완료: 스레드가 작업을 완료하면 결과를 반환하거나 다음 작업을 수행합니다.

예제 코드

다음은 C++11의 <thread>, <mutex>, <condition_variable>를 사용하여 간단한 스레드 풀을 구현한 예제 코드입니다.

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

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

    template<class F>
    void enqueue(F&& f) {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            tasks.emplace(std::forward<F>(f));
        }
        condition.notify_one();
    }

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

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

int main() {
    ThreadPool pool(4);

    for (int i = 0; i < 8; ++i) {
        pool.enqueue([i] {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            std::cout << "Task " << i << " completed" << std::endl;
        });
    }
}

위 코드는 C++11을 사용하여 간단한 스레드 풀을 구현한 것입니다. ThreadPool 클래스는 내부적으로 스레드들을 관리하고 작업을 큐에 넣어 작업을 실행합니다.

참고 자료

C++ 스레드 풀은 다양한 멀티스레드 애플리케이션에서 성능 향상을 위해 활용될 수 있습니다. 위 예제 코드를 참고하여 직접 스레드 풀을 구현해 보며 개념을 심화시키는 것을 추천합니다.