[c++] C++ 스레드 풀과 CPU 리소스 활용 최적화

소개

이번 포스트에서는 C++에서 스레드 풀을 구현하고 CPU 리소스를 효율적으로 활용하는 방법에 대해 알아볼 것입니다. 스레드 풀은 여러 작업을 동시에 처리할 수 있는 효율적인 방법을 제공하여 소프트웨어 성능을 향상시키는 데 도움이 됩니다.

C++ 스레드 풀 구현

우선, C++11부터 제공되는 <thread><mutex> 라이브러리를 사용하여 스레드 풀을 구현할 수 있습니다. 아래는 간단한 예제 코드입니다.

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

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

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

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

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

int main() {
    ThreadPool pool(4);
    for (int i = 0; i < 10; ++i) {
        pool.enqueue([i] {
            std::cout << "Task " << i << " is running\n";
            std::this_thread::sleep_for(std::chrono::seconds(1));
        });
    }
    return 0;
}

CPU 리소스 활용 최적화

스레드 풀을 사용하여 CPU 리소스를 효율적으로 활용하기 위해서는 작업을 적절히 분배하고 스레드 수를 적절히 조정해야 합니다. 이를 위해 다음과 같은 점을 고려할 수 있습니다.


이러한 방법을 통해 C++ 스레드 풀을 구현하고 CPU 리소스를 최적화하여 소프트웨어의 성능을 향상시킬 수 있습니다.

많은 질문이나 피드백이 있으시다면 이 페이지에서 자세히 알아보세요.