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

folly::CancellationToken — 코루틴·Future 취소 전파

· Hawk · 4분 읽기

한 줄 요약: CancellationToken은 코루틴·Future 트리에 협력적 취소를 전파한다. C++26 senders/receivers의 stop_token과 등가 모델로 Meta가 일찍 도입했다.

#동기

긴 비동기 작업이 외부 조건 (timeout, user cancel, parent failed)으로 멈춰야 할 때가 있다. callback-style code는 일반적으로 다음 둘 중 하나.

  1. boolean flag — 작업 시작 전 매번 체크. 누락 시 무한 hang.
  2. exception — 강제 unwind. 자원 leak/일관성 문제.

CancellationToken은 셋째 길이다. 명시적이고 합성 가능한 cancellation 신호.

folly::CancellationSource src;
auto token = src.getToken();
// 어딘가에서 cancel
src.requestCancellation();
// 토큰을 받은 쪽은 chunks마다 check 또는 await 자체가 cancel-aware
if (token.isCancellationRequested()) {
return;
}

이 모델은 cooperative. cancel 요청은 신호일 뿐, 실제로 멈추는 건 작업이 체크해서 결정.

#API

namespace folly {
class CancellationSource {
public:
CancellationSource();
bool requestCancellation() noexcept; // 한 번만 효력
CancellationToken getToken() const noexcept;
};
class CancellationToken {
public:
bool isCancellationRequested() const noexcept;
bool canBeCancelled() const noexcept;
CancellationCallback addCallback(/* func */); // cancel 시 호출
};
class CancellationCallback {
// RAII — destructor에서 unregister
};
}

세 클래스가 한 세트.

  • CancellationSource — 소유자. cancel을 발행.
  • CancellationToken — 소비자. cancel 여부를 조회.
  • CancellationCallback — token이 cancel될 때 호출되는 callback. RAII로 자동 unregister.

#Coroutine 통합

folly::coro::Task<int> LongCompute(folly::CancellationToken ct) {
for (int i = 0; i < 1000000; ++i) {
if (i % 1000 == 0 && ct.isCancellationRequested()) {
throw folly::OperationCancelled{};
}
// compute step
}
co_return 42;
}
folly::coro::Task<int> WithCancellation() {
folly::CancellationSource src;
std::thread([src]() mutable {
std::this_thread::sleep_for(std::chrono::seconds(5));
src.requestCancellation();
}).detach();
co_return co_await folly::coro::co_withCancellation(
src.getToken(), LongCompute(src.getToken()));
}

co_withCancellation이 token을 코루틴 frame에 attach. cancel-aware awaitable은 자동으로 깨어남.

#co_current_cancellation_token

folly::coro::Task<int> Helper() {
auto token = co_await folly::coro::co_current_cancellation_token;
if (token.isCancellationRequested()) {
throw folly::OperationCancelled{};
}
// ...
}

코루틴은 호출 트리에서 token을 상속한다. parent가 cancel되면 child도 cancel 신호를 받음.

#CancellationCallback — 동기적 cleanup

folly::coro::Task<void> ReadWithCleanup(int fd) {
auto token = co_await folly::coro::co_current_cancellation_token;
folly::CancellationCallback cb{token, [fd]() {
// cancel 시 호출 — fd close해서 read syscall 깨움
::shutdown(fd, SHUT_RDWR);
}};
// 이 read가 cancel signal을 직접 못 받음 (blocking)
auto bytes = co_await asyncRead(fd, buf, len);
co_return;
}

CancellationCallback이 token cancellation 시 동기적으로 호출된다. 이걸로 blocking syscall을 깨우는 트릭. socket shutdown, file close 같은 자리.

#트리 전파

CancellationToken tree propagation

folly::CancellationSource root;
auto rootToken = root.getToken();
folly::coro::Task<void> Parent() {
co_await folly::coro::co_withCancellation(
rootToken,
folly::coro::collectAll(
ChildA(), // 자동으로 rootToken 상속
ChildB(), // 자동으로 rootToken 상속
ChildC() // 자동으로 rootToken 상속
));
}

co_withCancellation이 한 번 attach하면 child Task들은 자동으로 같은 token을 본다. root가 cancel되면 셋 다 신호 받음. timer wheel, RPC fan-out 같은 패턴에 자연스럽다.

#MergeCancellationToken

auto merged = folly::cancellation_token_merge(token1, token2);
// merged는 두 token 중 하나라도 cancel되면 cancel

여러 cancel 조건을 OR 합성. timeout + user cancel을 동시에 표현.

#내부 구조

// folly/CancellationToken.h 약식
class CancellationState {
std::atomic<uint64_t> state_; // bit 0 = cancel requested, 상위 bits = ref count
std::list<CancellationCallback*> callbacks_;
std::mutex mu_;
};
// CancellationSource owns + 1 ref, each Token + 1 ref
// state_ atomic CAS로 cancel 요청 atomic하게
bool CancellationSource::requestCancellation() {
auto prev = state_->state_.fetch_or(kCancelBit);
if (prev & kCancelBit) return false; // 이미 cancel됨
// callbacks 호출 (lock 보호)
std::lock_guard lk(state_->mu_);
for (auto* cb : state_->callbacks_) {
cb->invoke();
}
return true;
}

핵심은 한 번만 cancel 가능 (atomic test-and-set), 그 시점에 모든 callback이 sync 호출.

#std::stop_token (C++20)과의 비교

항목std::stop_tokenfolly::CancellationToken
도입C++20folly (수년 전)
Source/Tokenstop_source / stop_tokenCancellationSource / CancellationToken
Callbackstop_callbackCancellationCallback
Coroutine 통합없음 (stdexec/P2300이 추가)co_withCancellation
표준stdfolly

C++20 std::stop_tokenstd::jthread의 멤버로 도입. 모델은 거의 동일. 차이는 코루틴 통합. stdexec/P2300이 표준 sender/receiver에 통합 중.

folly::CancellationTokenstd::stop_token과 형식적 일치 — 표준이 따라잡으면 마이그레이션 가능.

#코드 리뷰 포인트

  • 긴 작업에 cancellation 체크 없음 → 외부 조건 변화 시 영원히 hang.
  • requestCancellation() 후 작업이 즉시 멈추리라고 가정 → cooperative라 작업이 check할 때 멈춤.
  • callback 안에서 무거운 작업 또는 lock 획득 → cancel 발행 thread를 block.
  • token을 ref로 전달하는데 source가 먼저 소멸 → callback 호출 시점에 dangling 가능 (folly 구현은 shared state로 보호).
  • nested cancellation — child가 자체 source를 만들면 root cancel이 child까지 전파 안 됨. 명시적 attach.

#자주 보는 안티패턴

// 1. cancellation 무시
folly::coro::Task<int> Naive() {
for (int i = 0; i < 1e9; ++i) compute(); // cancel 체크 없음
co_return 0;
}
// 2. callback이 무거운 작업
folly::CancellationCallback cb{token, [&] {
ProcessHugeBuffer(); // cancel 발행 thread를 block
}};
// 3. token을 cancel-naive awaitable에 전달
co_await blockingRead(fd, buf, len); // ct가 있지만 read는 무관
// 4. exception 던지지 않고 silent return
if (ct.isCancellationRequested()) {
co_return -1; // 호출자가 cancel인지 fail인지 모름
}
// → folly::OperationCancelled throw가 표준 패턴

#실전 — RPC client timeout

folly::coro::Task<Response> CallRpc(Request req, std::chrono::milliseconds timeout) {
folly::CancellationSource src;
// timer가 cancel 발행
auto timer = std::thread([src, timeout]() mutable {
std::this_thread::sleep_for(timeout);
src.requestCancellation();
});
try {
auto result = co_await folly::coro::co_withCancellation(
src.getToken(), client_->send(std::move(req)));
timer.detach(); // 정상 완료 — timer 무시
co_return result;
} catch (const folly::OperationCancelled&) {
timer.detach();
throw RpcTimeoutException{};
}
}

timeout 자체가 cancellation으로 표현. RPC client가 cancel-aware하면 즉시 abort. 같은 패턴이 user-initiated cancel에도 그대로.

#정리

  • CancellationToken은 협력적 취소 신호 — 작업이 체크해야 멈춤.
  • Source/Token/Callback 셋이 한 세트. RAII로 자동 cleanup.
  • 코루틴 트리 전파 — co_withCancellation 한 번이면 자식 모두 상속.
  • std::stop_token (C++20)과 형식 일치 — 표준이 따라잡는 중.
  • timer, user cancel, parent failed 같은 다양한 cancellation 원인을 통일된 신호로.

#다음 편

Part 21로 넘어가 실험적 핵심 (observer, fbcode 패턴 모음)을 본다.

#관련 항목

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