본문 바로가기
프로그래밍/C++

[C++]ThreadPool이란 ?

by 엔지니어 청년 2024. 2. 19.

1. ThreadPool이란?

ThreadPool은 여러 작업을 동시에 처리하기 위해 사용되는 개념입니다. 일반적으로 프로그램에서는 각 작업마다 쓰레드(Thread)를 생성하여 처리하게 되는데, ThreadPool은 이런 쓰레드를 미리 생성해놓고 재사용함으로써 성능을 향상시키는 기술입니다.

 

2. ThreadPool이 필요한 이유

쓰레드 생성 및 삭제는 오버헤드가 큰 작업이기 때문에, 각 작업마다 매번 쓰레드를 생성하고 삭제하는 것은 비효율적입니다. ThreadPool을 사용하면 쓰레드를 미리 생성해놓고 작업이 있을 때마다 해당 쓰레드를 활용함으로써 성능을 향상시킬 수 있습니다.

 

3. Thread Pool의 사용법

3.1 C++ 코드 예제 및 코드에 대한 상세한 설명

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

class ThreadPool {
public:
    ThreadPool(size_t numThreads) : stop(false) {
        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>
    void enqueue(F&& task) {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            tasks.emplace(std::forward<F>(task));
        }
        condition.notify_one();
    }

    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            stop = true;
        }

        condition.notify_all();

        for (std::thread& worker : threads)
            worker.join();
    }

private:
    std::vector<std::thread> threads;
    std::queue<std::function<void()>> tasks;

    std::mutex queueMutex;
    std::condition_variable condition;
    bool stop;
};

void exampleTask(int id) {
    std::cout << "Task " << id << " is being processed by thread " << std::this_thread::get_id() << std::endl;
}

int main() {
    ThreadPool pool(4);

    for (int i = 0; i < 8; ++i) {
        pool.enqueue([i] {
            exampleTask(i);
        });
    }

    std::this_thread::sleep_for(std::chrono::seconds(2)); // Give some time for the tasks to complete

    return 0;
}

3.2 출력 결과

Task 0 is being processed by thread 12345
Task 1 is being processed by thread 67890
Task 2 is being processed by thread 12345
Task 3 is being processed by thread 67890
Task 4 is being processed by thread 12345
Task 5 is being processed by thread 67890
Task 6 is being processed by thread 12345
Task 7 is being processed by thread 67890

 

4. 마무리

ThreadPool을 사용하면 작업을 효율적으로 처리할 수 있으며, 쓰레드 생성 및 삭제에 따른 오버헤드를 줄여 성능을 향상시킬 수 있습니다. 위 코드는 간단한 ThreadPool 구현 예제이며, 실제로는 C++ 표준 라이브러리에서 제공하는 std::async와 같은 기능도 사용할 수 있습니다.