[c++] 스레드 풀과 스레드 풀 종료 방법

C++에서 스레드 풀(Thread Pool)은 멀티스레드 애플리케이션에서 작업을 실행하기 위한 스레드 그룹입니다. 스레드 풀은 미리 정의된 수의 스레드를 사용하여 작업을 할당하고 실행합니다. 이를 통해 작업을 병렬로 처리하여 애플리케이션의 성능을 향상시킬 수 있습니다.

C++에서의 스레드 풀 사용

C++11부터 스레드 라이브러리가 표준 라이브러리에 포함되었으며, 스레드 풀을 구현하기 위한 표준 라이브러리가 많이 사용됩니다. 일반적으로 std::threadstd::mutex를 사용하여 스레드를 관리하고 동기화합니다. 또한 C++ 표준 라이브러리에서 제공하는 std::asyncstd::future API를 사용하여 비동기 작업을 스레드 풀에 할당할 수 있습니다.

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

void task(int id) {
    // 작업을 수행
    std::cout << "Task " << id << " is running" << std::endl;
}

int main() {
    // 스레드 풀 생성
    std::vector<std::future<void>> futures;
    for (int i = 0; i < 5; ++i) {
        futures.push_back(std::async(std::launch::async, task, i));
    }

    // 모든 작업이 완료될 때까지 대기
    for (auto& f : futures) {
        f.get();
    }

    return 0;
}

위의 예제는 C++에서 스레드 풀을 사용하여 작업을 실행하는 간단한 예제입니다.

C++ 스레드 풀 종료 방법

스레드 풀을 종료할 때에는 몇 가지 주의할 점이 있습니다. 모든 작업이 완료될 때까지 기다리거나, 종료 신호를 보내어 작업을 취소할 수 있습니다. 또한 스레드 풀이 종료될 때 모든 리소스를 올바르게 정리하고 해제해야 합니다.

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

class ThreadPool {
public:
    ThreadPool(int numThreads) : m_done(false) {
        for (int i = 0; i < numThreads; ++i) {
            m_threads.push_back(std::thread([this]() {
                while (!m_done) {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(m_mutex);
                        m_condition.wait(lock, [this] { return m_done || !m_tasks.empty(); });
                        if (m_done && m_tasks.empty()) return;
                        task = std::move(m_tasks.front());
                        m_tasks.pop();
                    }
                    task();
                }
            }));
        }
    }

    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            m_done = true;
        }
        m_condition.notify_all();
        for (auto& thread : m_threads) {
            if (thread.joinable()) {
                thread.join();
            }
        }
    }

    template<class F>
    void enqueue(F&& f) {
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            m_tasks.push(std::function<void()>(f));
        }
        m_condition.notify_one();
    }

private:
    std::vector<std::thread> m_threads;
    std::queue<std::function<void()>> m_tasks;
    std::mutex m_mutex;
    std::condition_variable m_condition;
    bool m_done;
};

int main() {
    // 스레드 풀 생성
    ThreadPool pool(4);

    // 작업을 큐에 추가
    for (int i = 0; i < 8; ++i) {
        pool.enqueue([i] {
            std::cout << "Task " << i << " is running" << std::endl;
        });
    }

    // 스레드 풀 종료
    // pool.~ThreadPool(); // 명시적으로 호출할 필요는 없음

    return 0;
}

이 예제에서는 C++로 스레드 풀을 구현하고 있으며, ~ThreadPool 소멸자에서 스레드 풀을 안전하게 종료하고 있습니다.

스레드 풀을 사용하고 종료할 때에는 주의를 기울여 리소스 누수나 동기화 문제가 발생하지 않도록 해야 합니다.