C++ Parallel Algorithms | '병렬 알고리즘' 가이드
이 글의 핵심
C++ Parallel Algorithms: "병렬 알고리즘" 가이드. Execution Policy·병렬 정렬.
들어가며
C++17 병렬 알고리즘은 멀티코어 CPU를 활용하여 표준 알고리즘을 자동으로 병렬화합니다. std::execution::par를 추가하는 것만으로 std::sort, std::transform 등을 병렬 실행할 수 있습니다.
코딩 테스트 준비하며 깨달은 것
알고리즘 문제를 풀다 보면 “이게 실무에 무슨 도움이 될까?” 하는 의문이 들 때가 있습니다. 저도 그랬습니다. 하지만 실제 프로젝트에서 성능 문제에 부딪히면, 알고리즘 지식이 얼마나 중요한지 깨닫게 됩니다. 예를 들어, 사용자 검색 기능이 느려서 고민하다가 해시 테이블을 적용하니 응답 시간이 10초에서 0.1초로 줄어든 경험이 있습니다.
코딩 테스트는 단순히 취업을 위한 관문이 아니라, 문제 해결 능력을 키우는 훈련장입니다. 처음엔 브루트 포스로 풀다가, 시간 복잡도를 개선하는 과정에서 “아, 이렇게 생각하면 되는구나” 하는 깨달음을 얻을 때의 쾌감은 말로 표현하기 어렵습니다. 이 글에서는 단순히 정답 코드만 제시하는 게 아니라, 문제를 어떻게 접근하고 최적화하는지 사고 과정을 함께 공유하겠습니다.
1. Execution Policy
실행 정책 종류
#include <algorithm>
#include <execution>
#include <vector>
int main() {
std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};
// 1. seq: 순차 실행 (기본)
std::sort(std::execution::seq, v.begin(), v.end());
// 2. par: 병렬 실행
std::sort(std::execution::par, v.begin(), v.end());
// 3. par_unseq: 병렬 + 벡터화
std::sort(std::execution::par_unseq, v.begin(), v.end());
return 0;
}
Execution Policy 비교
| 정책 | 설명 | 특징 | 사용 시기 |
|---|---|---|---|
| seq | 순차 실행 | 단일 스레드 | 작은 데이터 |
| par | 병렬 실행 | 멀티스레드 | 큰 데이터, 독립적 연산 |
| par_unseq | 병렬 + 벡터화 | SIMD + 멀티스레드 | 큰 데이터, 단순 연산 |
2. 병렬 정렬
기본 정렬
#include <algorithm>
#include <execution>
#include <vector>
#include <iostream>
#include <chrono>
void benchmarkSort() {
std::vector<int> v1(10000000);
std::generate(v1.begin(), v1.end(), std::rand);
auto v2 = v1;
// 순차 정렬
auto start = std::chrono::high_resolution_clock::now();
std::sort(v1.begin(), v1.end());
auto end = std::chrono::high_resolution_clock::now();
auto seq_time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
// 병렬 정렬
start = std::chrono::high_resolution_clock::now();
std::sort(std::execution::par, v2.begin(), v2.end());
end = std::chrono::high_resolution_clock::now();
auto par_time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "순차 정렬: " << seq_time.count() << "ms" << std::endl;
std::cout << "병렬 정렬: " << par_time.count() << "ms" << std::endl;
std::cout << "속도 향상: " << (double)seq_time.count() / par_time.count() << "x" << std::endl;
}
int main() {
benchmarkSort();
return 0;
}
출력 (4코어):
순차 정렬: 2341ms
병렬 정렬: 687ms
속도 향상: 3.4x
3. 병렬 변환
transform
#include <algorithm>
#include <execution>
#include <vector>
#include <cmath>
#include <iostream>
int main() {
std::vector<double> data(10000000);
std::iota(data.begin(), data.end(), 1.0);
// 병렬 제곱근 계산
std::transform(std::execution::par,
data.begin(), data.end(), data.begin(),
{ return std::sqrt(x); });
std::cout << "첫 5개: ";
for (int i = 0; i < 5; ++i) {
std::cout << data[i] << " ";
}
std::cout << std::endl;
return 0;
}
출력:
첫 5개: 1 1.41421 1.73205 2 2.23607
for_each
#include <algorithm>
#include <execution>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v(1000000);
std::iota(v.begin(), v.end(), 1);
// 병렬 for_each
std::for_each(std::execution::par, v.begin(), v.end(),
{
x = x * x; // 제곱
});
std::cout << "v[99]: " << v[99] << std::endl; // 10000
return 0;
}
4. 병렬 집계
reduce
#include <numeric>
#include <execution>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v(10000000);
std::iota(v.begin(), v.end(), 1);
// 병렬 reduce (합계)
long long sum = std::reduce(std::execution::par,
v.begin(), v.end(), 0LL);
std::cout << "합: " << sum << std::endl;
return 0;
}
출력:
합: 50000005000000
transform_reduce
#include <numeric>
#include <execution>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v(1000000);
std::iota(v.begin(), v.end(), 1);
// 병렬 제곱합
long long sum_of_squares = std::transform_reduce(
std::execution::par,
v.begin(), v.end(),
0LL,
std::plus<>(),
{ return static_cast<long long>(x) * x; }
);
std::cout << "제곱합: " << sum_of_squares << std::endl;
return 0;
}
5. 병렬 검색
find
#include <algorithm>
#include <execution>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v(10000000);
std::iota(v.begin(), v.end(), 1);
// 병렬 find
auto it = std::find(std::execution::par, v.begin(), v.end(), 5000000);
if (it != v.end()) {
std::cout << "찾음: " << *it << std::endl;
std::cout << "인덱스: " << std::distance(v.begin(), it) << std::endl;
}
return 0;
}
count_if
#include <algorithm>
#include <execution>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v(10000000);
std::generate(v.begin(), v.end(), std::rand);
// 병렬 count_if (짝수 개수)
auto count = std::count_if(std::execution::par, v.begin(), v.end(),
{ return x % 2 == 0; });
std::cout << "짝수 개수: " << count << std::endl;
return 0;
}
6. 자주 발생하는 문제
문제 1: 작은 데이터
#include <algorithm>
#include <execution>
#include <vector>
#include <chrono>
#include <iostream>
void benchmarkSmallData() {
std::vector<int> small(100);
std::generate(small.begin(), small.end(), std::rand);
auto v1 = small;
auto v2 = small;
// 순차
auto start = std::chrono::high_resolution_clock::now();
std::sort(v1.begin(), v1.end());
auto end = std::chrono::high_resolution_clock::now();
auto seq_time = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
// 병렬 (오버헤드 > 이득)
start = std::chrono::high_resolution_clock::now();
std::sort(std::execution::par, v2.begin(), v2.end());
end = std::chrono::high_resolution_clock::now();
auto par_time = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << "순차: " << seq_time.count() << "μs" << std::endl;
std::cout << "병렬: " << par_time.count() << "μs" << std::endl;
}
int main() {
benchmarkSmallData();
// 순차: 5μs
// 병렬: 150μs (오버헤드)
return 0;
}
문제 2: 공유 상태 (데이터 레이스)
#include <algorithm>
#include <execution>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v(1000000);
std::iota(v.begin(), v.end(), 1);
int sum = 0;
// ❌ 데이터 레이스
std::for_each(std::execution::par, v.begin(), v.end(), [&](int x) {
sum += x; // 여러 스레드가 sum에 동시 접근
});
std::cout << "잘못된 합: " << sum << std::endl; // 예상과 다름
// ✅ reduce 사용
long long correct_sum = std::reduce(std::execution::par, v.begin(), v.end(), 0LL);
std::cout << "올바른 합: " << correct_sum << std::endl;
return 0;
}
문제 3: 예외 처리
#include <algorithm>
#include <execution>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v = {1, 2, -3, 4, -5};
try {
// 병렬 실행 중 예외
std::for_each(std::execution::par, v.begin(), v.end(), {
if (x < 0) {
throw std::runtime_error("음수 발견");
}
});
} catch (const std::exception& e) {
// 여러 스레드에서 예외 발생 가능
// 첫 번째 예외만 잡힘
std::cout << "예외: " << e.what() << std::endl;
}
return 0;
}
문제 4: 순서 의존 연산
#include <algorithm>
#include <execution>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
// ❌ 순서 의존 (레이스)
std::for_each(std::execution::par, v.begin(), v.end(), [&](int& x) {
x = v[0] + 1; // v[0]을 여러 스레드가 읽음 (위험)
});
// ✅ 독립적 연산
std::for_each(std::execution::par, v.begin(), v.end(), {
x = x * 2; // 각 요소 독립적
});
for (int x : v) std::cout << x << " ";
std::cout << std::endl;
return 0;
}
7. 지원 알고리즘
주요 알고리즘
#include <algorithm>
#include <numeric>
#include <execution>
// 정렬
std::sort(std::execution::par, v.begin(), v.end());
std::stable_sort(std::execution::par, v.begin(), v.end());
std::partial_sort(std::execution::par, v.begin(), v.begin() + 10, v.end());
// 검색
std::find(std::execution::par, v.begin(), v.end(), 42);
std::find_if(std::execution::par, v.begin(), v.end(), pred);
std::binary_search(std::execution::par, v.begin(), v.end(), 42);
// 변환
std::transform(std::execution::par, v.begin(), v.end(), v.begin(), func);
std::for_each(std::execution::par, v.begin(), v.end(), func);
// 집계
std::reduce(std::execution::par, v.begin(), v.end(), 0);
std::transform_reduce(std::execution::par, v.begin(), v.end(), 0, plus, func);
// 복사
std::copy(std::execution::par, v1.begin(), v1.end(), v2.begin());
std::copy_if(std::execution::par, v1.begin(), v1.end(), v2.begin(), pred);
// 기타
std::count(std::execution::par, v.begin(), v.end(), 42);
std::count_if(std::execution::par, v.begin(), v.end(), pred);
std::all_of(std::execution::par, v.begin(), v.end(), pred);
std::any_of(std::execution::par, v.begin(), v.end(), pred);
8. 실전 예제: 이미지 처리
#include <algorithm>
#include <execution>
#include <vector>
#include <cmath>
#include <iostream>
struct Pixel {
unsigned char r, g, b;
};
class ImageProcessor {
std::vector<Pixel> pixels;
int width, height;
public:
ImageProcessor(int w, int h) : width(w), height(h) {
pixels.resize(w * h);
}
// 병렬 그레이스케일 변환
void toGrayscale() {
std::for_each(std::execution::par, pixels.begin(), pixels.end(),
{
unsigned char gray = static_cast<unsigned char>(
0.299 * p.r + 0.587 * p.g + 0.114 * p.b
);
p.r = p.g = p.b = gray;
});
}
// 병렬 밝기 조정
void adjustBrightness(int delta) {
std::for_each(std::execution::par, pixels.begin(), pixels.end(),
[delta](Pixel& p) {
auto clamp = {
return std::max(0, std::min(255, val));
};
p.r = clamp(p.r + delta);
p.g = clamp(p.g + delta);
p.b = clamp(p.b + delta);
});
}
// 병렬 블러 (간단한 평균)
void blur() {
auto original = pixels;
std::for_each(std::execution::par, pixels.begin(), pixels.end(),
[&](Pixel& p) {
int idx = &p - &pixels[0];
int x = idx % width;
int y = idx / width;
// 3x3 평균 (간단화)
int r_sum = 0, g_sum = 0, b_sum = 0, count = 0;
for (int dy = -1; dy <= 1; ++dy) {
for (int dx = -1; dx <= 1; ++dx) {
int nx = x + dx;
int ny = y + dy;
if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
int nidx = ny * width + nx;
r_sum += original[nidx].r;
g_sum += original[nidx].g;
b_sum += original[nidx].b;
++count;
}
}
}
p.r = r_sum / count;
p.g = g_sum / count;
p.b = b_sum / count;
});
}
// 병렬 픽셀 카운트
int countBrightPixels(int threshold) {
return std::count_if(std::execution::par, pixels.begin(), pixels.end(),
[threshold](const Pixel& p) {
int brightness = (p.r + p.g + p.b) / 3;
return brightness > threshold;
});
}
};
int main() {
ImageProcessor img(1920, 1080);
img.toGrayscale();
img.adjustBrightness(20);
img.blur();
int bright = img.countBrightPixels(128);
std::cout << "밝은 픽셀: " << bright << std::endl;
return 0;
}
정리
핵심 요약
- 병렬 알고리즘: C++17 멀티코어 활용
- Execution Policy: seq, par, par_unseq
- 성능: 큰 데이터에서 2-4배 향상
- 주의: 데이터 레이스, 순서 의존 금지
- 적용: 10,000개 이상, 독립적 연산
병렬 알고리즘 효과
| 데이터 크기 | 연산 복잡도 | 병렬 효과 | 권장 정책 |
|---|---|---|---|
| < 1,000 | 낮음 | 없음 | seq |
| 1,000-10,000 | 낮음 | 낮음 | seq |
| > 10,000 | 낮음 | 중간 | par |
| > 10,000 | 높음 | 높음 | par |
| > 100,000 | 단순 | 매우 높음 | par_unseq |
실전 팁
사용 원칙:
- 큰 데이터 (10,000개 이상)에만 사용
- 계산 집약적 연산에 효과적
- 독립적 연산만 병렬화
- 공유 상태 피하기
성능:
- 프로파일링으로 효과 측정
- 작은 데이터는 오버헤드 큼
- 메모리 집약적 연산은 효과 낮음
- CPU 코어 수에 따라 효과 다름
주의사항:
- 데이터 레이스 방지 (
std::atomic,reduce) - 예외 처리 신중 (
std::terminate가능) - 순서 의존 연산 금지
- 디버깅 어려움 (TSan 사용)
다음 단계
- C++ Execution Policy
- C++ Thread
- C++ Atomic
관련 글
심화 부록: 구현·운영 관점
이 부록은 앞선 본문에서 다룬 주제(「C++ Parallel Algorithms | ‘병렬 알고리즘’ 가이드」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.
내부 동작과 핵심 메커니즘
flowchart TD A[입력·요청·이벤트] --> B[파싱·검증·디코딩] B --> C[핵심 연산·상태 전이] C --> D[부작용: I/O·네트워크·동시성] D --> E[결과·관측·저장]
sequenceDiagram participant C as 클라이언트/호출자 participant B as 경계(런타임·게이트웨이·프로세스) participant D as 의존성(API·DB·큐·파일) C->>B: 요청/이벤트 B->>D: 조회·쓰기·RPC D-->>B: 지연·부분 실패·재시도 가능 B-->>C: 응답 또는 오류(코드·상관 ID)
- 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
- 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
- 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
- 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.
프로덕션 운영 패턴
| 영역 | 운영 관점 질문 |
|---|---|
| 관측성 | 요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가 |
| 안전성 | 입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가 |
| 신뢰성 | 재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가 |
| 성능 | 캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가 |
| 배포 | 롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가 |
| 용량 | 피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가 |
스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.
확장 예시: 엔드투엔드 미니 시나리오
앞선 본문 주제(「C++ Parallel Algorithms | ‘병렬 알고리즘’ 가이드」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.
- 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
- 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
- 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
- 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
- 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
ctx = newCorrelationId()
validated = validateSchema(request)
authorize(validated, ctx)
result = domainCore(validated)
persistOrEmit(result, idempotentKey)
recordMetrics(ctx, latency, outcome)
return result
문제 해결(Troubleshooting)
| 증상 | 가능 원인 | 조치 |
|---|---|---|
| 간헐적 실패 | 레이스, 타임아웃, 외부 의존성, DNS | 최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검 |
| 성능 저하 | N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스 | 프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거 |
| 메모리 증가 | 캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납 | 상한·TTL·힙/FD 스냅샷 비교 |
| 빌드·배포만 실패 | 환경 변수, 권한, 플랫폼 차이, lockfile | CI 로그와 로컬 diff, 런타임·이미지 버전 핀 |
| 설정 불일치 | 프로필·시크릿·기본값, 리전 | 스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화 |
| 데이터 불일치 | 비멱등 재시도, 부분 쓰기, 캐시 무효화 누락 | 멱등 키·아웃박스·트랜잭션 경계 재검토 |
권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.
배포 전에는 git add → git commit → git push 후 npm run deploy 순서를 권장합니다.
자주 묻는 질문 (FAQ)
Q. 이 내용을 실무에서 언제 쓰나요?
A. Everything about C++ Parallel Algorithms : principles, complexity, implementation. Master algorithms quickly with proble… 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.
Q. 선행으로 읽으면 좋은 글은?
A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.
Q. 더 깊이 공부하려면?
A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ Execution Policy | ‘실행 정책’ 가이드
- C++ Range Algorithms | ‘범위 알고리즘’ 가이드
- C++ Algorithm Reverse | reverse·rotate·reverse_copy 완벽 정리
이 글에서 다루는 키워드 (관련 검색어)
C++, parallel, 알고리즘, performance, C++17 등으로 검색하시면 이 글이 도움이 됩니다.