C++에서는 스레드 풀을 구현하기 위해 여러 가지 방법을 사용할 수 있습니다. 스레드 풀은 작업을 처리하는 데 사용되는 스레드의 풀로, 이를 통해 작업을 효율적으로 처리할 수 있습니다.
1. C++11 스레드 라이브러리 사용
C++11부터는 std::thread
와 std::future
를 사용하여 스레드를 생성하고 작업을 실행할 수 있습니다. 스레드 풀을 구현하기 위해서는 스레드를 미리 생성하고 작업을 큐에 추가하여 스레드 풀에서 작업을 가져와 처리합니다.
다음은 C++11을 사용하여 간단한 스레드 풀을 구현하는 예제 코드입니다.
#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(size_t numThreads) : running(true) {
for (size_t i = 0; i < numThreads; ++i) {
workers.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queueMutex);
this->condition.wait(lock, [this]{
return !this->running || !this->tasks.empty();
});
if (!this->running && 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);
running = false;
}
condition.notify_all();
for (auto &worker : workers) {
worker.join();
}
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queueMutex;
std::condition_variable condition;
bool running;
};
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;
});
}
return 0;
}
위 코드는 C++11의 std::thread
, std::mutex
, std::condition_variable
및 std::queue
를 사용하여 간단한 스레드 풀을 구현한 예제입니다. ThreadPool
클래스를 사용하여 작업을 스레드 풀에 추가하고, 필요한 만큼의 스레드가 작업을 처리합니다.
2. Third-party 라이브러리 사용
C++에서는 Boost 및 Intel TBB와 같은 third-party 라이브러리를 사용하여 스레드 풀을 구현할 수도 있습니다. 이러한 라이브러리는 스레드 풀을 관리하고 작업을 처리하는 데 도움이 되는 다양한 기능을 제공합니다.
예를 들어, Boost 라이브러리의 boost::asio::thread_pool
클래스는 스레드 풀을 쉽게 구현하고 사용할 수 있는 방법을 제공합니다.
C++에서의 스레드 풀 구현 방법에 대해 간단히 살펴보았습니다. 각각의 방법은 프로젝트의 요구 사항 및 성능에 따라 선택할 수 있으며, 스레드 풀을 사용하여 병렬 처리를 효율적으로 수행할 수 있습니다.
참고 문헌:
- https://en.cppreference.com/w/
- https://www.boost.org/doc/libs/1_77_0/doc/html/boost_asio/reference/thread_pool.html