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

folly::InlineExecutor — 호출자 thread에서 즉시 실행

· Hawk · 4분 읽기

한 줄 요약: InlineExecutoradd(fn)그 자리에서 호출한다. 가장 단순한 Executor지만 동시에 가장 잘못 쓰이는 Executor다.

#동기 — Executor가 없는 Executor

folly::Executor는 추상 인터페이스다.

class Executor {
public:
virtual void add(Func) = 0;
virtual uint8_t getNumPriorities() const { return 1; }
};

이 인터페이스를 가장 단순하게 구현하면 다음과 같다.

class InlineExecutor : public Executor {
public:
void add(Func f) override { f(); }
};

callback을 schedule하지 않고 호출자 thread에서 그대로 실행한다. 비동기성을 없애는 Executor다.

#Executor 4가지 모델 비교

Inline은 4가지 흔한 executor 모델 중 가장 단순한 끝에 있다.

Executor models compared

Inline → Queued (single worker) → Fixed pool → Work-stealing 순으로 동시성과 복잡도가 올라간다. Inline은 0 오버헤드지만 deadlock과 stack overflow 위험이 있고, work-stealing은 로드밸런싱이 좋지만 cross-thread 동기화 비용이 든다.

#사용 사례

Folly Executor types

#1. 단위 테스트

TEST(MyFuture, ChainExecution) {
auto sf = compute()
.deferValue([](int x) { return x + 1; })
.deferValue([](int x) { return x * 2; });
// 테스트 thread에서 모든 callback이 동기적으로 실행됨
auto v = std::move(sf).via(&folly::InlineExecutor::instance()).get();
EXPECT_EQ(v, 86);
}

테스트는 결정적이어야 한다. InlineExecutor는 callback이 언제, 어디서 실행되는지 보장하므로 race가 없다.

#2. 이미 결정된 값의 단축 경로

folly::SemiFuture<Cache> getCachedOr(int id) {
if (auto c = cache.find(id)) {
return folly::makeSemiFuture(*c); // 동기 결과
}
return fetchAsync(id);
}
// caller
getCachedOr(id)
.via(&folly::InlineExecutor::instance()) // cache hit이면 inline
.thenValue([](Cache c) { return process(c); });

cache hit일 때 thread switch 없이 바로 처리한다. cache miss라면 fetchAsync가 적절한 executor를 내부적으로 사용한다.

#3. SemiFuture를 강제로 명시적으로 inline 실행

auto v = computeSemi().via(&folly::InlineExecutor::instance()).get();

.via(executor)가 빠진 채 .get()을 부르면 내부적으로 InlineExecutor가 쓰인다. 의도가 inline이면 명시적으로 적는 게 코드 리뷰에 좋다.

#구현 — folly::InlineExecutor

folly/executors/InlineExecutor.h
namespace folly {
class InlineExecutor : public Executor {
public:
static InlineExecutor& instance() {
static InlineExecutor x;
return x;
}
void add(Func f) override {
f();
}
};
} // namespace folly

코드가 10줄도 안 된다. singleton으로 노출되며 어디서든 folly::InlineExecutor::instance()로 접근한다.

#변형 — InlineLikeExecutor / QueuedImmediateExecutor

folly/executors/QueuedImmediateExecutor.h
class QueuedImmediateExecutor : public Executor {
public:
void add(Func f) override {
if (q_.empty()) {
q_.push(std::move(f));
while (!q_.empty()) {
q_.front()();
q_.pop();
}
} else {
q_.push(std::move(f));
}
}
private:
static thread_local std::queue<Func> q_;
};

QueuedImmediateExecutor재진입을 막는다. callback A가 실행 중 callback B를 add하면 InlineExecutor는 B를 A 중간에 실행해 stack을 쌓는다. QueuedImmediateExecutor는 B를 큐에 넣어 A가 끝난 뒤 실행한다.

// 위험 — InlineExecutor
folly::Promise<int> p;
folly::InlineExecutor::instance().add([&] {
p.setValue(1); // 또 다른 callback을 즉시 실행 — stack 깊어짐
});
// 안전 — QueuedImmediateExecutor
folly::QueuedImmediateExecutor::instance().add([&] {
p.setValue(1); // queue에 들어가서 현재 callback 끝난 뒤 실행
});

긴 Future 체인에서는 QueuedImmediateExecutor가 stack overflow를 막는다.

#위험 — 잘못 쓰일 때

#1. 의도 없이 사용 (가장 흔함)

auto v = computeSemi().get(); // 내부적으로 InlineExecutor

compute()어디서 도는지 코드에서 보이지 않는다. 어떤 thread의 어떤 lambda 안인지 추적 불가.

#2. Stack overflow

folly::Future<int> f = ...;
for (int i = 0; i < 100'000; ++i) {
f = std::move(f).via(&folly::InlineExecutor::instance())
.thenValue([](int x) { return x + 1; });
}
f.get(); // stack overflow 가능

각 thenValue가 즉시 다음 thenValue를 호출하므로 callback이 nested된다. 1만~10만 단위에서 stack 한계를 넘는다. QueuedImmediateExecutor가 해결책이다.

#3. Latency hiding

folly::SemiFuture<Result> handleRequest(Request req) {
return validate(req)
.via(&folly::InlineExecutor::instance()) // bad
.thenValue([](auto r) { return process(r); });
}

caller가 RPC handler thread에서 handleRequest를 부르면 모든 callback이 그 thread에서 실행된다. 다른 요청이 starve된다.

#코드 리뷰 포인트

  • .via(&InlineExecutor::instance()) 또는 .get() 직접 호출에 이유가 있는가? 없으면 적절한 executor로 바꾼다.
  • Future 체인이 깊은가? InlineExecutor 대신 QueuedImmediateExecutor를 고려한다.
  • 테스트에서만 InlineExecutor를 쓰는가? production code path와 분리한다.
  • SemiFuture가 항상 즉시 완료되는가? 그렇다면 InlineExecutor가 안전하다.

#자주 보는 안티패턴

// 1. production hot path에서 .get() 호출
folly::SemiFuture<R> handleRpc(Req r) {
auto v = doInternal(r).get(); // RPC thread block
return processFurther(v);
}
// 2. 긴 체인을 InlineExecutor로
auto f = base;
for (auto& step : steps) {
f = std::move(f).via(&inline).thenValue(step); // stack 폭발 위험
}
// 3. shared executor를 쓰지 않는 이유로 InlineExecutor
// 그냥 적절한 thread pool을 만들어라
// 4. InlineExecutor를 명시 없이 사용
sf.thenValue(...) // SemiFuture에는 .thenValue 없음 — 컴파일 에러
sf.via(...).thenValue(...) // executor 명시

#std::execution과 비교

P2300의 std::execution::inline_scheduler(가칭)도 같은 의미다. 호출자 thread에서 즉시 실행한다. 사용 가이드라인도 비슷할 것이다.

#정리

  • InlineExecutor는 callback을 caller thread에서 즉시 실행하는 가장 단순한 Executor다.
  • 테스트, 단축 경로, 명시적 inline 표현에 적합하다.
  • 의도 없이 사용하면 어디서 callback이 도는지 추적이 불가능하다.
  • 긴 체인에서는 stack overflow 위험이 있다. QueuedImmediateExecutor를 사용한다.
  • production handler에서는 거의 항상 부적합하다.
  • .via(InlineExecutor)항상 의도를 적은 흔적이어야 한다.

#다음 편

Part 3-02: CPUThreadPoolExecutor에서 CPU-bound 작업을 위한 thread pool을 본다.

#관련 항목

Folly Code Review · 14 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 사용의 실전