folly::Future 분석 — std::future의 한계를 넘는 composable async
한 줄 요약:
std::future는 값을 가져가는 통로에 그친다.folly::Future는 continuation, executor binding, 예외 전파를 모두 다루는 조립 가능한 async primitive다.
#동기 — std::future는 왜 부족한가
C++11이 std::future를 도입했을 때 가장 큰 결함이 둘이었다.
.then없음 — Future가 완료된 뒤 콜백을 거는 방법이 없다.std::async+std::future조합은 값을 한 번 받는 패턴만 표현한다.- executor 개념 없음 — Future가 어디서 실행되는지 표준에 명세되지 않는다.
std::async(std::launch::async, ...)는 OS thread를 매번 새로 만들 수도, 안 만들 수도 있다.
C++23의 std::expected, C++26 후보의 senders/receivers가 이 문제를 풀고 있지만 지금 production에서 쓸 도구는 아니다. Folly는 2014년부터 이 빈자리를 채워왔다.
#API 한눈에
#include <folly/futures/Future.h>#include <folly/executors/CPUThreadPoolExecutor.h>
folly::CPUThreadPoolExecutor pool(4);
// 1) 즉시 완료된 Futurefolly::SemiFuture<int> sf = folly::makeSemiFuture(42);
// 2) executor에 bind → Futurefolly::Future<int> f = std::move(sf).via(&pool);
// 3) continuation 체인auto result = std::move(f) .thenValue([](int x) { return x * 2; }) .thenValue([](int x) { return std::to_string(x); }) .thenError(folly::tag_t<std::exception>{}, [](auto const& e) { return std::string{"error: "} + e.what(); }) .get(); // blocking wait세 줄 안에 비동기 계산, 에러 처리, 결과 회수가 모두 표현된다. std::future로 같은 패턴을 짜면 별도의 thread, condition variable, try/catch가 필요하다.
#핵심 타입 세 가지
| 타입 | 역할 |
|---|---|
Promise<T> | 값 또는 예외를 생산자가 채우는 쪽 |
SemiFuture<T> | executor 미바인딩 상태 — 계산은 끝났을 수 있지만 continuation은 어디서 돌릴지 모름 |
Future<T> | executor 바인딩 완료 — continuation을 그 executor에서 실행 |
이 셋의 분리가 std::future와의 결정적 차이다. std::future는 두 단계(생산/소비)지만 Folly는 세 단계(생산/실행자/소비)다.
#Promise/Future 일반 모델
타입 수와 별개로, Promise는 생산자 쪽, Future는 소비자 쪽이라는 분리 자체는 어느 future 구현에도 공통이다.
생산자가 shared state에 값을 set하면 소비자가 그 값을 get한다. .then 체인은 콜백 중첩 대신 평탄한 파이프라인을 만들어 callback hell을 해소한다.
#내부 구조 — Core
// folly/futures/detail/Core.h (요약)template <class T>class Core { public: enum class State { Start, OnlyResult, // result만 있음 (callback 없음) OnlyCallback, // callback만 있음 (result 없음) OnlyCallbackAllowInline, Proxy, Done, // result + callback 모두 처리 Empty, };
std::atomic<State> state_; folly::Try<T> result_; Callback callback_; Executor::KeepAlive<> executor_;};Core는 FSM으로 생산자와 소비자의 순서 무관성을 처리한다. setValue()가 먼저 와도 되고 thenValue()가 먼저 와도 된다. 둘 다 도착하면 executor_로 callback을 schedule한다.
// folly/futures/detail/Core.cpp (개념)void Core::setResult(Try<T> t) { State expected = State::Start; if (state_.compare_exchange_strong(expected, State::OnlyResult)) { result_ = std::move(t); return; // callback이 나중에 옴 } // 이미 callback이 등록됨 → 즉시 실행 result_ = std::move(t); state_ = State::Done; executor_->add([cb = std::move(callback_), r = std::move(result_)]() mutable { cb(std::move(r)); });}compare_exchange_strong으로 atomic FSM 전이를 한다. 두 thread가 동시에 도착해도 race가 없다.
#Continuation 모델
// SemiFuture<int>::thenValue (개념)template <class F>auto SemiFuture<int>::thenValue(F&& fn) && { using R = std::invoke_result_t<F, int>; auto [p, f] = folly::makePromiseContract<R>(); // 새 Promise/Future 쌍 std::move(*this).setCallback_([p = std::move(p), fn = std::move(fn)](Try<int>&& t) mutable { if (t.hasException()) { p.setException(std::move(t.exception())); } else { p.setWith([&] { return fn(*std::move(t)); }); } }); return std::move(f);}각 .thenValue()는 새 Promise/Future 쌍을 만들고 그것을 다음 단계에 넘긴다. 체인은 linked list와 비슷하게 자란다.
#std::future / std::async와의 비교
| 항목 | std::future | folly::Future |
|---|---|---|
| continuation | 없음 (C++23 .then 제안 중) | .thenValue, .thenTry, .thenError |
| executor | 없음 (launch policy만) | .via(Executor*) |
| exception 전파 | set_exception 단방향 | Try<T> 통합 |
| 결합 | 없음 | collect, collectAll, collectAny |
| timeout | wait_for 만 | .within(Duration) |
| retry | 없음 | folly::futures::retrying(...) |
| cancellation | 없음 | CancellationToken |
| coroutine 통합 | 없음 | folly::coro::Task (별도) |
std::future는 Future를 값으로 한 번 받는 인터페이스에 머문다. Folly는 Future를 데이터플로우의 노드로 본다.
#간단한 실전 예
folly::IOThreadPoolExecutor io(2);folly::CPUThreadPoolExecutor cpu(4);
folly::SemiFuture<std::string> fetchUrl(std::string url);folly::SemiFuture<Parsed> parse(std::string body);
folly::SemiFuture<Parsed> getParsed(std::string url) { return fetchUrl(std::move(url)) .via(&io) // I/O는 IO pool .thenValue([cpu = &cpu](std::string body) { return parse(std::move(body)) .via(cpu); // parse는 CPU pool });}I/O와 CPU 작업을 서로 다른 executor로 분리하는 패턴이 한 줄씩이다. std::future로는 별도의 thread pool 추상화를 직접 만들어야 한다.
#코드 리뷰 포인트
.via()가 누락됐는가? SemiFuture를 그대로.get()하거나.thenValue()하면 어디서 실행될지 불명확하다..get()이 hot path에 있는가? blocking이다..then체인으로 풀어야 한다.- 체인 중간에 captured by reference가 있는가? lambda 수명이 Future 수명보다 길면 dangling이다.
- 예외가 silent하게 swallow되는가?
.thenError를 두지 않으면.get()에서 throw된다.
#자주 보는 안티패턴
// 1. SemiFuture를 그대로 .get()auto v = computeSemi().get(); // executor 없음 → InlineExecutor 또는 deadlock
// 2. Future를 멤버로 보관class Worker { folly::Future<int> f_; // continuation 체인이 살아 있어야 의미 있음};
// 3. 매 호출마다 새 thread poolvoid handle() { folly::CPUThreadPoolExecutor pool(4); // 매번 생성/파괴 — 비용 폭증 compute().via(&pool).get();}
// 4. exception swallowcompute().thenValue([](int x) { return parse(x); }).get();// parse가 throw하면 get()에서 다시 throw — caller가 모를 수 있음#정리
folly::Future는 continuation, executor binding, exception 전파를 통합한 async primitive다.- 핵심 타입은
Promise<T>/SemiFuture<T>/Future<T>세 가지다. - 내부
Core<T>가 atomic FSM으로 생산자/소비자 순서 무관성을 보장한다. std::future와 다른 사고 모델이다. 값이 아니라 데이터플로우 노드다.- C++26 senders/receivers가 도착하면 이 패턴은 표준으로 흡수될 가능성이 높다.
#다음 편
Part 2-02: Promise / makeFuture에서 Future를 만드는 두 가지 길을 자세히 본다.
#관련 항목
Folly Code Review · 7 of 89
- 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
- 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
- 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
- 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
- 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
- 6 Folly production validation 문화 — peta-scale에서 단련된 코드
- 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
- 8 folly::Promise·makeFuture — Future를 만드는 두 길
- 9 folly::SemiFuture vs Future — executor binding의 명시화
- 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
- 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
- 12 folly::Future retry·window·via — 제어 흐름 조합자
- 13 folly::fibers 분석 — M:N stackful coroutine
- 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
- 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
- 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
- 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
- 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
- 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
- 20 folly::IOBufQueue — chain의 push/pull 추상화
- 21 folly::io::Cursor·RWCursor — chain 위의 stream
- 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
- 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
- 24 folly::FBString 분석 — SSO + COW 구현
- 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
- 26 folly::StringPiece — string_view 호환 분석
- 27 folly Join·Split utilities — 문자열 분해와 결합
- 28 folly::to·tryTo — text↔num 변환 분석
- 29 folly Conv Customization — 사용자 타입 지원
- 30 folly Conv 성능 비교 — sprintf·stringstream 대비
- 31 folly::F14ValueMap vs std::unordered_map
- 32 folly::F14NodeMap — stable pointer가 필요할 때
- 33 folly::F14VectorMap — cache-friendly iteration
- 34 folly::F14FastMap — auto-select 동작
- 35 folly F14 internals — SIMD probing 메커니즘
- 36 folly::small_vector — inline storage 분석
- 37 folly::FixedString — compile-time string
- 38 folly::AtomicHashMap — lock-free read 분석
- 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
- 40 folly::EvictingCacheMap — LRU 구현 분석
- 41 folly::Synchronized — lock wrapper 패턴
- 42 folly::SharedMutex 분석
- 43 folly::Baton — one-shot wait 동기화
- 44 folly::RWSpinLock 분석
- 45 folly::PicoSpinLock — 1-byte spinlock
- 46 folly::ProducerConsumerQueue — SPSC 큐 분석
- 47 folly::MPMCQueue — multi-producer multi-consumer
- 48 folly::UnboundedQueue — 동적 크기 lock-free
- 49 folly::fibers::Channel — Go-like channel
- 50 folly::dynamic — JSON-like dynamic type 분석
- 51 folly JSON conversion — toJson·parseJson
- 52 folly dynamic ↔ struct — manual marshaling
- 53 folly dynamic Visitor pattern — type별 분기
- 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
- 55 folly::SingletonVault 분석 — 등록·소멸·의존성
- 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
- 57 folly::ExceptionWrapper — type-erased exception holder
- 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
- 59 folly::Optional vs std::optional
- 60 folly::Function vs std::function
- 61 folly::Lazy — 지연 초기화 wrapper
- 62 folly Meta 스타일 code review 패턴
- 63 folly anti-patterns — 잘못 쓰면 std보다 느림
- 64 folly vs std 선택 기준 분석
- 65 folly::coro 개요 — production C++20 코루틴 어댑터
- 66 folly::coro::Task — lazy single-shot 코루틴
- 67 folly::coro::AsyncGenerator — 비동기 스트림
- 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
- 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
- 70 folly::Expected — 결과 또는 오류
- 71 folly::Try — Future 결과 wrapper
- 72 folly::Try vs Expected 선택 기준
- 73 folly::Range — 일반 iterator pair
- 74 folly::Uri — URL 파서
- 75 folly Fingerprint64·128 — 분산 hash
- 76 folly SpookyHashV2 — fast non-crypto hash
- 77 folly::Init — main() 부트스트랩
- 78 folly::Indestructible — global lifetime 패턴
- 79 folly::MicroLock — 1-byte 락
- 80 folly::MicroSpinLock — 가장 좁은 spin lock
- 81 folly::format — legacy formatter 분석
- 82 folly::demangle — typeid 디망글링
- 83 folly::DynamicConverter — dynamic ↔ struct
- 84 folly::RecordIO — append-only 로그 파일 포맷
- 85 folly::io::Compression — zstd·lz4·snappy wrapper
- 86 folly::AsyncIO — io_uring·Linux AIO
- 87 folly::CancellationToken — 코루틴·Future 취소 전파
- 88 folly::observer — hot config의 atomic refresh
- 89 fbcode 패턴 모음 — folly 사용의 실전
관련 글
folly::Promise·makeFuture — Future를 만드는 두 길
folly::Promise로 비동기 완료를 표현하고, makeFuture/makeSemiFuture로 이미 결정된 값을 Future 인터페이스에 올린다.
같은 시리즈에서 이어 읽기
folly::CancellationToken — 코루틴·Future 취소 전파
CancellationSource/Token의 전파 모델 — coroutine·Future·callback 트리에서 협력적 취소.
같은 시리즈에서 이어 읽기
folly::Try — Future 결과 wrapper
Try<T>의 세 상태 (value/exception/empty), Future 내부에서의 역할, exception_wrapper와의 관계.
같은 시리즈에서 이어 읽기
이 글을 참조하는 글 (6)
- folly::coro 개요 — production C++20 코루틴 어댑터 — Folly Code Review
- folly::EventBase 분석 — libevent 이벤트 루프의 핵심 — Folly Code Review
- folly::fibers 분석 — M:N stackful coroutine — Folly Code Review
- folly::SemiFuture vs Future — executor binding의 명시화 — Folly Code Review
- folly::Promise·makeFuture — Future를 만드는 두 길 — Folly Code Review
- Folly production validation 문화 — peta-scale에서 단련된 코드 — Folly Code Review