본문으로 건너뛰기
Folly Code Review · 7/89

folly::Promise·makeFuture — Future를 만드는 두 길

· Hawk · 3분 읽기

한 줄 요약: Promise<T>나중에 값/예외를 채우는 생산자 측 핸들이고, makeFuture 계열은 이미 결정된 값을 Future 인터페이스에 올리는 단축 길이다.

#동기 — 왜 두 가지 길이 필요한가

비동기 계산의 결과를 Future로 표현할 때 두 가지 상황이 있다.

  1. 결과가 아직 없음 — I/O 완료, timer 발화, 다른 thread의 작업 종료 등을 기다림
  2. 결과가 이미 있음 — 캐시 hit, validation 실패로 즉시 실패, default 값 반환

(1)은 Promise<T>로 표현한다. 생산자는 Promise를 들고 있다가 결과가 나오면 setValue()를 호출한다. (2)는 makeFuture(value) / makeSemiFuture(value)로 표현한다. 새 Promise를 만들고 즉시 set하는 한 줄짜리 단축이다.

두 길의 결과물은 같다. 동일한 Core<T>를 가리키는 Future/SemiFuture가 만들어진다.

#Promise — 생산자 측 핸들

#include <folly/futures/Promise.h>
#include <folly/futures/Future.h>
folly::Promise<int> p;
folly::SemiFuture<int> sf = p.getSemiFuture();
// 다른 thread에서
std::thread([p = std::move(p)]() mutable {
std::this_thread::sleep_for(std::chrono::seconds(1));
p.setValue(42);
}).detach();
int v = std::move(sf).via(&inlineExecutor).get(); // 42

Promise는 한 번만 set할 수 있다. 두 번 set하면 PromiseAlreadySatisfied 예외가 throw된다.

// folly/futures/Promise.h (요약)
template <class T>
class Promise {
public:
Promise() : Promise(makeEmptyConstruct()) {
core_ = new detail::Core<T>();
}
void setValue(T&& v) {
throwIfFulfilled();
core_->setResult(Try<T>(std::move(v)));
}
void setException(exception_wrapper ew) {
throwIfFulfilled();
core_->setResult(Try<T>(std::move(ew)));
}
template <class F>
void setWith(F&& fn) {
throwIfFulfilled();
core_->setResult(makeTryWith(std::forward<F>(fn)));
}
SemiFuture<T> getSemiFuture(); // 한 번만 호출 가능
Future<T> getFuture(); // SemiFuture + InlineExecutor
private:
detail::Core<T>* core_;
};

setWith()함수 호출이 throw할 수 있을 때 편리하다.

folly::Promise<int> p;
p.setWith([] { return mayThrow(); });
// throw하면 자동으로 setException로 변환

#makeFuture / makeSemiFuture

이미 결정된 값을 Future로 wrap한다.

folly::SemiFuture<int> ok = folly::makeSemiFuture(42);
folly::SemiFuture<int> ng = folly::makeSemiFuture<int>(
folly::make_exception_wrapper<std::runtime_error>("bad"));
// void Future
folly::SemiFuture<folly::Unit> done = folly::makeSemiFuture();

Unitvoid를 1급 타입으로 다루기 위한 sentinel이다. Future<void>는 표준에 있지만 generic 코드에서 다루기 불편해 Folly는 Future<Unit>을 선호한다.

// folly/futures/Future.h (요약)
template <class T>
SemiFuture<typename std::decay_t<T>> makeSemiFuture(T&& t) {
return SemiFuture<...>(Try<...>(std::forward<T>(t)));
}
template <class T>
SemiFuture<T> makeSemiFuture(Try<T> t) {
return SemiFuture<T>(std::move(t));
}
SemiFuture<Unit> makeSemiFuture(); // void 대체

#Try — 값 또는 예외의 통합 컨테이너

Promise::setValue/setException은 내부적으로 Try<T>로 변환된다. Try<T>std::variant<T, exception_wrapper>에 가깝다.

// folly/Try.h (요약)
template <class T>
class Try {
public:
Try(T&& v);
Try(exception_wrapper ew);
bool hasValue() const;
bool hasException() const;
T& value() &; // hasException이면 throw
T&& value() &&;
T const& operator*() const;
T& operator*() &;
T&& operator*() &&;
exception_wrapper& exception();
};

Try<T>는 단순한 컨테이너지만, Future 체인 전체가 이 위에 돌아간다. 모든 .thenTry(callback)Try<T>를 인자로 받고 Try<R>을 반환한다.

folly::Future<int> f = folly::makeFuture(42)
.thenTry([](folly::Try<int> t) -> int {
if (t.hasException()) return -1;
return *t * 2;
});

#makePromiseContract — 쌍을 한 번에

auto [p, sf] = folly::makePromiseContract<int>();
// p: Promise<int>
// sf: SemiFuture<int> — p와 같은 Core 공유

C++17 structured binding으로 깔끔하게 표현된다. Promise와 Future를 별도로 만들어 연결할 때 보일러플레이트를 줄인다.

// folly/futures/Promise.h (요약)
template <class T>
std::pair<Promise<T>, SemiFuture<T>> makePromiseContract() {
auto p = Promise<T>();
auto sf = p.getSemiFuture();
return {std::move(p), std::move(sf)};
}

#std::promise와의 차이

// std::promise
std::promise<int> p;
std::future<int> f = p.get_future();
p.set_value(42);
int v = f.get(); // 42
// folly::Promise
folly::Promise<int> p;
folly::SemiFuture<int> sf = p.getSemiFuture();
p.setValue(42);
int v = std::move(sf).via(&inlineExecutor).get(); // 42

비슷해 보이지만 두 가지가 다르다.

  1. continuationstd::promise의 future는 .then이 없다. f.get()만 가능.
  2. exception APIstd::promise::set_exception(std::exception_ptr)은 타입 정보를 잃는다. Promise::setException(exception_wrapper)은 타입을 보존한다.

exception_wrapper복사 가능한 exception 핸들로, type-erased 상태에서도 with_exception<E>()로 타입별 분기가 가능하다.

folly::exception_wrapper ew = folly::make_exception_wrapper<MyError>("bad");
if (ew.with_exception([](MyError& e) { handleMy(e); })) {
// matched
}

#코드 리뷰 포인트

  • Promise의 수명이 Future보다 짧지 않은가? Promise가 먼저 파괴되면 BrokenPromise 예외로 Future가 완료된다. silent failure가 아닌 명시적 실패다.
  • getFuture() vs getSemiFuture()? 가능하면 후자를 쓴다. getFuture()는 InlineExecutor에 자동 바인딩되어 어디서 callback이 도는지 불명확하다.
  • Promise를 두 번 set하지는 않는가? thread 두 곳에서 set하면 둘 중 하나가 throw된다.
  • makeFuture에 큰 객체를 by value로 넘기지 않는가? makeFuture(std::move(x)) 또는 makeFuture<X>(args...) 사용.

#자주 보는 안티패턴

// 1. Promise를 lambda에서 capture by reference
folly::Promise<int> p;
auto f = p.getSemiFuture();
std::thread([&p]() { p.setValue(42); }).detach();
// p가 stack에서 사라지면 dangling — 반드시 std::move로 capture
// 2. Promise를 set한 뒤 다시 set
p.setValue(1);
p.setValue(2); // throws PromiseAlreadySatisfied
// 3. getFuture()를 두 번
auto f1 = p.getFuture();
auto f2 = p.getFuture(); // throws FutureAlreadyRetrieved
// 4. setException(std::exception_ptr)
std::exception_ptr ep = std::make_exception_ptr(MyError{});
p.setException(folly::exception_wrapper(ep));
// 타입 정보가 흐려짐 — 가능하면 make_exception_wrapper<MyError>(...) 사용

#정리

  • Promise<T>나중에 값/예외를 채우는 생산자 핸들이다. 한 번만 set 가능하다.
  • makeFuture/makeSemiFuture이미 결정된 값을 Future 인터페이스에 올리는 단축이다.
  • 두 길의 결과물은 같은 Core<T>를 가리킨다.
  • makePromiseContract<T>()로 한 번에 쌍을 만든다.
  • exception_wrapperstd::exception_ptr보다 풍부한 type-erased 예외 표현이다.
  • Promise 수명이 Future보다 짧으면 BrokenPromise 예외가 명시적으로 발생한다.

#다음 편

Part 2-03: SemiFuture vs Future에서 executor 바인딩의 차이가 무엇을 결정하는지 본다.

#관련 항목

Folly Code Review · 8 of 89

  1. 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
  2. 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
  3. 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
  4. 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
  5. 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
  6. 6 Folly production validation 문화 — peta-scale에서 단련된 코드
  7. 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
  8. 8 folly::Promise·makeFuture — Future를 만드는 두 길
  9. 9 folly::SemiFuture vs Future — executor binding의 명시화
  10. 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
  11. 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
  12. 12 folly::Future retry·window·via — 제어 흐름 조합자
  13. 13 folly::fibers 분석 — M:N stackful coroutine
  14. 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
  15. 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
  16. 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
  17. 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
  18. 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
  19. 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
  20. 20 folly::IOBufQueue — chain의 push/pull 추상화
  21. 21 folly::io::Cursor·RWCursor — chain 위의 stream
  22. 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
  23. 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
  24. 24 folly::FBString 분석 — SSO + COW 구현
  25. 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
  26. 26 folly::StringPiece — string_view 호환 분석
  27. 27 folly Join·Split utilities — 문자열 분해와 결합
  28. 28 folly::to·tryTo — text↔num 변환 분석
  29. 29 folly Conv Customization — 사용자 타입 지원
  30. 30 folly Conv 성능 비교 — sprintf·stringstream 대비
  31. 31 folly::F14ValueMap vs std::unordered_map
  32. 32 folly::F14NodeMap — stable pointer가 필요할 때
  33. 33 folly::F14VectorMap — cache-friendly iteration
  34. 34 folly::F14FastMap — auto-select 동작
  35. 35 folly F14 internals — SIMD probing 메커니즘
  36. 36 folly::small_vector — inline storage 분석
  37. 37 folly::FixedString — compile-time string
  38. 38 folly::AtomicHashMap — lock-free read 분석
  39. 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
  40. 40 folly::EvictingCacheMap — LRU 구현 분석
  41. 41 folly::Synchronized — lock wrapper 패턴
  42. 42 folly::SharedMutex 분석
  43. 43 folly::Baton — one-shot wait 동기화
  44. 44 folly::RWSpinLock 분석
  45. 45 folly::PicoSpinLock — 1-byte spinlock
  46. 46 folly::ProducerConsumerQueue — SPSC 큐 분석
  47. 47 folly::MPMCQueue — multi-producer multi-consumer
  48. 48 folly::UnboundedQueue — 동적 크기 lock-free
  49. 49 folly::fibers::Channel — Go-like channel
  50. 50 folly::dynamic — JSON-like dynamic type 분석
  51. 51 folly JSON conversion — toJson·parseJson
  52. 52 folly dynamic ↔ struct — manual marshaling
  53. 53 folly dynamic Visitor pattern — type별 분기
  54. 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
  55. 55 folly::SingletonVault 분석 — 등록·소멸·의존성
  56. 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
  57. 57 folly::ExceptionWrapper — type-erased exception holder
  58. 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
  59. 59 folly::Optional vs std::optional
  60. 60 folly::Function vs std::function
  61. 61 folly::Lazy — 지연 초기화 wrapper
  62. 62 folly Meta 스타일 code review 패턴
  63. 63 folly anti-patterns — 잘못 쓰면 std보다 느림
  64. 64 folly vs std 선택 기준 분석
  65. 65 folly::coro 개요 — production C++20 코루틴 어댑터
  66. 66 folly::coro::Task — lazy single-shot 코루틴
  67. 67 folly::coro::AsyncGenerator — 비동기 스트림
  68. 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
  69. 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
  70. 70 folly::Expected — 결과 또는 오류
  71. 71 folly::Try — Future 결과 wrapper
  72. 72 folly::Try vs Expected 선택 기준
  73. 73 folly::Range — 일반 iterator pair
  74. 74 folly::Uri — URL 파서
  75. 75 folly Fingerprint64·128 — 분산 hash
  76. 76 folly SpookyHashV2 — fast non-crypto hash
  77. 77 folly::Init — main() 부트스트랩
  78. 78 folly::Indestructible — global lifetime 패턴
  79. 79 folly::MicroLock — 1-byte 락
  80. 80 folly::MicroSpinLock — 가장 좁은 spin lock
  81. 81 folly::format — legacy formatter 분석
  82. 82 folly::demangle — typeid 디망글링
  83. 83 folly::DynamicConverter — dynamic ↔ struct
  84. 84 folly::RecordIO — append-only 로그 파일 포맷
  85. 85 folly::io::Compression — zstd·lz4·snappy wrapper
  86. 86 folly::AsyncIO — io_uring·Linux AIO
  87. 87 folly::CancellationToken — 코루틴·Future 취소 전파
  88. 88 folly::observer — hot config의 atomic refresh
  89. 89 fbcode 패턴 모음 — folly 사용의 실전