folly::SemiFuture vs Future — executor binding의 명시화
한 줄 요약:
SemiFuture<T>는 executor에 바인딩되지 않은 Future다. 라이브러리 API의 반환 타입으로 SemiFuture를 강제하면 caller가 executor 결정권을 갖는다.
#동기 — executor가 누구의 책임인가
비동기 함수가 Future<T>를 반환하면 어디서 callback이 도는지가 함수 안에 고정된다. caller는 그 executor가 자기 thread context와 맞는지 알 수 없다. 다음 코드는 잘못된 thread에서 GUI를 갱신할 위험이 있다.
folly::Future<Image> loadImage(std::string path) { static folly::CPUThreadPoolExecutor pool(4); return folly::via(&pool, [path] { return decodeImage(path); });}
// GUI thread에서loadImage("a.png").thenValue([](Image img) { ui->display(img); // BUG: GUI thread가 아닐 수 있음});loadImage의 caller는 callback이 어디서 도는지 보이지 않는다. Folly의 해법은 executor 결정을 caller에게 떠넘기는 것이다.
folly::SemiFuture<Image> loadImage(std::string path) { return folly::makeSemiFuture() .deferValue([path](auto) { return decodeImage(path); });}
// callerloadImage("a.png") .via(&guiExecutor) // executor 명시 .thenValue([](Image img) { ui->display(img); // 안전 });}SemiFuture를 반환하면 caller가 .via(executor)를 반드시 호출해야 다음 단계로 갈 수 있다. 컴파일러가 강제하지 않지만 API 관례로 강제된다.
#SemiFuture의 인터페이스
// folly/futures/Future.h (요약)template <class T>class SemiFuture { public: // executor 바인딩 — Future로 전환 Future<T> via(Executor* e) &&; Future<T> via(Executor::KeepAlive<> e) &&;
// executor 없이 callback 등록 — DrivableExecutor 위에서만 의미 template <class F> SemiFuture<U> deferValue(F&& fn) &&; template <class F> SemiFuture<U> deferError(F&& fn) &&; template <class F> SemiFuture<U> defer(F&& fn) &&;
// blocking T get() &&; T getVia(DrivableExecutor* e) &&;
// 그 외 bool isReady() const; SemiFuture<T> wait() &&;};deferValue/deferError는 executor가 정해질 때까지 callback을 보류한다. 나중에 .via(e)가 호출되면 모든 deferred callback이 그 executor에서 실행된다.
#Future의 인터페이스 (요약)
template <class T>class Future { public: Executor* getExecutor() const;
template <class F> Future<U> thenValue(F&& fn) &&; template <class F> Future<U> thenError(folly::tag_t<E>, F&& fn) &&; template <class F> Future<U> thenTry(F&& fn) &&;
Future<T> via(Executor* e) &&; // executor 재바인딩 Future<T> within(Duration); Future<T> onTimeout(Duration, F);
// SemiFuture로 역변환 — executor 분리 SemiFuture<T> semi() &&;};Future는 bound executor가 있는 상태이므로 .thenValue를 바로 호출할 수 있다. SemiFuture는 그렇지 않다.
#변환 흐름
makeSemiFuture(v) ──▶ SemiFuture<T> ──.via(e)──▶ Future<T> │Promise<T>.getSemiFuture() ──▶ SemiFuture<T> │ │Promise<T>.getFuture() ──▶ Future<T> (InlineExecutor) ▼ .thenValue / .thenError ... │ ▼ Future<U> 또는 .semi() ──▶ SemiFuture<U>getFuture()는 InlineExecutor에 자동 바인딩된다. 이는 어디서 callback이 도는지가 caller의 thread에 의존한다는 뜻이고, 거의 항상 명확한 표현이 아니다. OSS 코드 리뷰에서는 getSemiFuture() 사용을 권장한다.
#라이브러리 API 권장 패턴
// 잘못된 패턴 — executor가 함수에 고정folly::Future<Result> doWork(); // 어디서 callback이 도는지 불명
// 권장 패턴 — caller가 결정folly::SemiFuture<Result> doWork(); // .via(e)를 caller가 호출
// 모듈 boundary에서의 강제namespace mylib { folly::SemiFuture<Response> Handle(Request); // SemiFuture로 export}내부 구현은 자유롭게 Future를 쓰지만 공개 API는 SemiFuture로 통일한다. Folly 자체의 모든 public API가 이 규칙을 따른다.
#defer vs via — 두 가지 callback 등록
folly::SemiFuture<int> sf = computeAsync();
// 방법 A — defer: executor 결정 전 등록, 나중에 via로 일괄 실행sf .deferValue([](int x) { return x + 1; }) .deferValue([](int x) { return x * 2; }) .via(&pool) .thenValue([](int x) { return std::to_string(x); }) .get();
// 방법 B — 즉시 via, 이후 then 사용sf .via(&pool) .thenValue([](int x) { return x + 1; }) .thenValue([](int x) { return x * 2; }) .get();A는 SemiFuture가 라이브러리 boundary를 넘어 caller까지 흘러갈 때 유용하다. B는 같은 스코프 안에서 명확하다.
#내부 구현 — Executor 보관
// folly/futures/detail/Core.h (개념)template <class T>class Core { Executor::KeepAlive<> executor_; // SemiFuture는 nullptr, Future는 bound // ...};
// .via 호출 시template <class T>Future<T> SemiFuture<T>::via(Executor::KeepAlive<> e) && { this->getCore().setExecutor(std::move(e)); return Future<T>(detail::EmptyConstruct{}, this->getCore());}Executor::KeepAlive<>는 executor에 대한 참조 카운트 증가를 보장한다. callback이 실행될 때까지 executor가 destroyed되지 않는다.
#std::executor 제안과의 관계
C++26 후보의 std::execution::scheduler/sender/receiver는 같은 문제를 푼다.
Folly std::execution (P2300)───────────────────── ─────────────────────SemiFuture<T> sender (unbound)Future<T> connected senderExecutor scheduler.via(e) on(scheduler, sender).thenValue(f) then(sender, f).get() sync_wait(sender)개념적으로 거의 1
대응이다. P2300이 표준에 도착하면 Folly 사용자는 점진적으로 이전할 수 있다.#코드 리뷰 포인트
- public API가 Future를 반환하는가? SemiFuture로 바꾼다.
getFuture()사용?getSemiFuture()로 바꾸고 caller가.via(e)를 호출하게 한다.- 체인 중간에
.via()가 없이.then을 부르는가? SemiFuture는 컴파일 에러가 난다. Future라면 어디서 도는지 명확해야 한다. .semi()로 다시 SemiFuture를 만드는 이유가 있는가? 라이브러리 경계를 넘기는 경우에만 의미 있다.
#자주 보는 안티패턴
// 1. public API가 Futurefolly::Future<Result> handleRequest(Request); // 잘못
// 2. SemiFuture에 InlineExecutor를 강제auto v = computeSemi().via(&folly::InlineExecutor::instance()).get();// continuation이 호출자 thread에서 도는 게 의도였는가?
// 3. .via 누락 후 .getauto v = computeSemi().get(); // 내부적으로 InlineExecutor 사용 — 의도 불명
// 4. 매 호출마다 .via를 잊는다mylib::Handle(req) .thenValue([](auto r) { ... }); // SemiFuture라 컴파일 에러#정리
SemiFuture<T>는 executor에 바인딩되지 않은 Future다..via(e)로 Future로 전환된다.- 라이브러리 public API의 반환 타입으로 SemiFuture를 강제하면 caller가 executor 결정권을 갖는다.
getFuture()는 InlineExecutor에 자동 바인딩되므로 거의 항상 모호하다.getSemiFuture()를 쓴다.deferValue/deferError는 executor 결정 전 callback을 보류한다.- 개념적으로 C++26 senders/receivers와 1 대응이다.
#다음 편
Part 2-04: .then / .thenValue / .thenError에서 continuation API의 세부를 본다.
#관련 항목
Folly Code Review · 9 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::InlineExecutor — 호출자 thread에서 즉시 실행
InlineExecutor는 add()의 caller thread에서 callback을 그 자리에서 실행한다. 테스트와 단축 경로에 적합하지만 production hot path에는 위험하다.
같은 시리즈에서 이어 읽기
folly::coro::Task — lazy single-shot 코루틴
Task<T>의 lazy start, executor 바인딩, scheduleOn, 값/예외 전파 — production async의 기본 단위.
같은 시리즈에서 이어 읽기
folly::coro 개요 — production C++20 코루틴 어댑터
folly::coro의 위치 — std 코루틴 위에 Task/AsyncGenerator/Mutex를 쌓아 production async를 가능하게 한 이유.
같은 시리즈에서 이어 읽기
이 글을 참조하는 글 (8)
- folly::coro::Task — lazy single-shot 코루틴 — Folly Code Review
- folly::coro 개요 — production C++20 코루틴 어댑터 — Folly Code Review
- folly anti-patterns — 잘못 쓰면 std보다 느림 — Folly Code Review
- folly::ExceptionWrapper — type-erased exception holder — Folly Code Review
- folly::Singleton try_get·try_get_fast — TLS-cached 접근 — Folly Code Review
- folly::InlineExecutor — 호출자 thread에서 즉시 실행 — Folly Code Review
- folly::Promise·makeFuture — Future를 만드는 두 길 — Folly Code Review
- folly::Future 분석 — std::future의 한계를 넘는 composable async — Folly Code Review