이번에는 C++에서 스레드 풀을 사용하여 작업을 완료하는 방법에 대해 알아보겠습니다. 스레드 풀은 여러 작업을 처리하는 데 유용한 방법 중 하나입니다. 특히, 여러 개의 작업을 비동기적으로 수행하고 완료 상황을 제어해야 할 때 유용합니다.
스레드 풀이란?
스레드 풀은 미리 정해진 개수의 스레드를 생성해 두고, 이를 이용하여 여러 작업을 처리하는 방식입니다. 주요한 이점은 스레드를 반복해서 생성하고 삭제하는 오버헤드를 줄일 수 있어서 효율적으로 사용할 수 있다는 점입니다.
C++에서의 스레드 풀 사용
C++11부터는 <thread>
헤더 파일을 통해 스레드를 손쉽게 다룰 수 있습니다. 스레드 풀을 사용하기 위해서는 일반적으로 스레드를 생성하고 관리하는 라이브러리를 사용하게 되는데, 예를 들어 Boost.Asio, Intel TBB(Threading Building Blocks) 등을 이용할 수 있습니다.
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
class ThreadPool {
public:
ThreadPool(size_t num_threads) : stop(false) {
for (size_t i = 0; i < num_threads; ++i) {
threads.emplace_back(
[this] {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
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 f) {
{
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.emplace(f);
}
condition.notify_one();
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
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 queue_mutex;
std::condition_variable condition;
bool stop;
};
int main() {
ThreadPool pool(4);
for (int i = 0; i < 8; ++i) {
pool.enqueue([i] {
std::cout << "Task " << i << " is being processed" << std::endl;
});
}
return 0;
}
위 예시 코드는 C++에서 스레드 풀을 구현한 간단한 예제입니다. ThreadPool 클래스를 통해 여러 개의 작업을 스레드 풀에 추가하고, 모든 작업이 완료될 때까지 기다릴 수 있습니다.
작업 완료 처리
위의 예시 코드에서 ThreadPool
클래스는 작업을 완료할 때까지 기다리는 enqueue()
함수를 제공합니다. 따라서 작업이 완료되었는지 여부를 확인하고 싶을 때는 해당 기능을 활용할 수 있습니다.
결론
C++에서는 스레드 풀을 사용하여 여러 작업을 효율적으로 처리하고 완료 상황을 제어할 수 있습니다. 이를 통해 병렬 처리의 효율성을 높일 수 있으며, 작업 완료 상황을 체계적으로 다룰 수 있습니다.
참고:
- https://en.cppreference.com/w/cpp/thread/thread
- https://www.boost.org/doc/libs/1_77_0/doc/html/boost_asio.html
- https://www.threadingbuildingblocks.org/