[c++] 스레드 풀과 스레드 풀 사용 사례

스레드 풀은 여러 작업을 처리하기 위해 미리 생성된 스레드를 사용하는 소프트웨어 디자인 패턴입니다. C++에서는 스레드 풀을 사용하여 작업을 효율적으로 처리할 수 있습니다. 이 글에서는 C++에서 스레드 풀을 어떻게 구현하고 사용하는지, 그리고 실제 사례를 살펴보겠습니다.

스레드 풀 구현하기

C++11부터는 <thread> 헤더와 <future> 헤더를 사용하여 스레드와 비동기 작업을 쉽게 다룰 수 있게 되었습니다. 스레드 풀을 구현하는 한 가지 방법은 <thread><future>를 사용하여 스레드를 생성하고 관리하는 것입니다.

#include <iostream>
#include <vector>
#include <thread>
#include <future>

class ThreadPool {
public:
    explicit ThreadPool(size_t numThreads) {
        for (size_t i = 0; i < numThreads; ++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, class... Args>
    auto enqueue(F &&f, Args &&... args) -> std::future<decltype(f(args...))> {
        using returnType = decltype(f(args...));
        auto task = std::make_shared<std::packaged_task<returnType()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));

        std::future<returnType> res = task->get_future();
        {
            std::unique_lock<std::mutex> lock(queueMutex);

            if (stop) {
                throw std::runtime_error("enqueue on stopped ThreadPool");
            }

            tasks.emplace([task]() { (*task)(); });
        }
        condition.notify_one();
        return res;
    }

    ~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;
};

위의 코드는 C++에서 스레드 풀을 구현하는 예시입니다. ThreadPool 클래스는 지정된 스레드 수만큼의 스레드를 만들고 작업을 저장하는 큐를 관리합니다.

스레드 풀 사용 사례

스레드 풀을 사용하는 예시로는 병렬 처리가 필요한 작업이 있을 때가 있습니다. 예를 들어, 파일 다운로드, 이미지 처리, 네트워크 요청 등과 같이 시간이 많이 소요되는 작업을 병렬로 처리하여 전체 속도를 높일 수 있습니다.

아래는 스레드 풀을 사용하여 간단한 작업을 병렬로 처리하는 예시 코드입니다.

void longRunningTask(int taskId) {
    std::this_thread::sleep_for(std::chrono::seconds(3));
    std::cout << "Task " << taskId << " done" << std::endl;
}

int main() {
    ThreadPool pool(4);

    for (int i = 0; i < 8; ++i) {
        pool.enqueue(longRunningTask, i);
    }

    std::this_thread::sleep_for(std::chrono::seconds(5)); // 모든 작업이 완료될 때까지 대기
    return 0;
}

위의 예시 코드는 8개의 작업을 스레드 풀에 넣어 병렬로 실행하는 것을 보여줍니다.

결론

C++에서 스레드 풀을 구현하고 사용하는 방법을 살펴보았습니다. 스레드 풀은 여러 작업을 효율적으로 처리하고 병렬로 실행할 수 있는 강력한 도구입니다. 따라서 스레드 풀은 C++ 프로그래밍에서 성능을 개선하고 병렬 처리를 구현하는 데 유용하게 활용될 수 있습니다.