folly::IOBuf shared semantics — clone·unshare·takeOwnership
한 줄 요약: IOBuf의 buffer와 node는 별개다.
clone은 buffer를 공유하고 node를 새로 만든다.unshare는 buffer를 분리한다. 이 구분이 zero-copy의 안전성을 결정한다.
#동기 — share의 두 층위
IOBuf의 구조를 다시 본다.
buffer는 실제 byte 영역과 SharedInfo다. node는 그 buffer를 가리키는 IOBuf 객체다.
share할 수 있는 것은 buffer다. 여러 IOBuf node가 같은 buffer를 가리킬 수 있다. 각 node는 독립된 chain link, 독립된 data_/length를 가질 수 있다(같은 buffer의 다른 부분).
#clone — 같은 buffer를 가리키는 새 node
auto a = folly::IOBuf::create(1024);a->append(100);
auto b = a->clone();// b는 새 node, a와 같은 buffer를 가리킴// a->data() == b->data()// SharedInfo.refcount = 2clone은 얕은 복사다. node는 새로 만들지만 buffer는 공유한다. ref-count가 0이 될 때까지 buffer는 살아 있다.
#unshare — buffer copy로 분리
auto b = a->clone(); // ref-count = 2b->unshare(); // b만의 buffer로 복사 — ref-count = 1, 1
b->writableData()[0] = 'x'; // a는 영향 없음unshare는 write 전 분리다. 자기만의 buffer로 copy하고 ref-count를 분리한다. copy-on-write의 수동 버전이다.
fbstring이 write를 가로채 자동으로 unshare를 수행한다면, IOBuf는 명시적으로 unshare()를 부르는 모델이다. 같은 원리, 다른 정책 — IOBuf의 buffer는 보통 더 크고 unshare 비용이 더 크기 때문에 의사 결정을 호출자에게 위임한다.
// folly/io/IOBuf.cpp (개념)void IOBuf::unshareOne() { if (isSharedOne()) { // 새 buffer 할당 + copy auto newBuf = ...; std::memcpy(newBuf, data_, length_); // 기존 SharedInfo decref, 새 SharedInfo decrementRefcount(); setNewBuffer(newBuf); }}#clone vs cloneOne vs cloneAsValue
auto chain = ...; // 3-node chain
auto a = chain->clone(); // 전체 chain clone, ref-count 모두 shareauto b = chain->cloneOne(); // 첫 node만 clone, 나머지 chain은 없음auto c = chain->cloneAsValue(); // unique_ptr 대신 IOBuf 값clone()— 전체 chain의 모든 node sharecloneOne()— 단일 node만 sharecloneCoalesced()— 새 buffer 하나로 chain 합치기 (zero-copy 아님)
#takeOwnership — 외부 메모리 wrap
uint8_t* mem = (uint8_t*)malloc(1024);auto buf = folly::IOBuf::takeOwnership( mem, 1024, // 시작, 크기 [mem](void*, void*) { free(mem); }); // free callback
// buf의 ref-count가 0이 되면 callback 호출callback의 두 인자는 (data, userData)다. userData는 SharedInfo에 보관할 추가 context다.
// mmap 예void* mapped = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);auto buf = folly::IOBuf::takeOwnership( mapped, size, [size](void* p, void*) { munmap(p, size); });#wrapBuffer — read-only, lifetime 미관리
const char* msg = "hello";auto buf = folly::IOBuf::wrapBuffer(msg, 5);// buf의 ref-count = 0 (관리 안 함)// msg의 lifetime은 caller가 보장wrapBuffer는 zero-cost wrap이다. ref-count도 없고, free 콜백도 없다. caller가 lifetime을 보장해야 한다.
좋은 사용:
- string literal
- static buffer
- caller가 lifetime을 확실히 길게 잡은 buffer
위험:
- stack-local buffer
- temporary container의 buffer
- lambda capture로 share되는 buffer
#SharedInfo — 내부
// folly/io/IOBuf.h (요약)struct SharedInfo { FreeFunction freeFn; // free 콜백 void* userData; // 콜백에 전달할 context std::atomic<uint32_t> refcount{1}; uint8_t externallyShared{0}; // 외부 reference 표시};refcount는 atomic이다. 모든 clone/unshare/destroy는 atomic operation을 거친다. 비용은 uncontended 시 ~5ns, contended 시 훨씬 더.
#externallyShared — 외부 참조 추적
auto a = folly::IOBuf::create(1024);auto b = a->clone();
a->markExternallySharedOne(); // 외부 코드가 a의 buffer를 본다고 표시
b->isShared(); // true — refcount > 1b->isExternallyShared(); // true — externallyShared 비트externallyShared는 코드 외부에서 buffer를 보고 있을 때 사용한다. 예를 들어 raw pointer를 다른 thread에 넘긴 경우. refcount로는 안 잡힌다.
#chain의 ref-count
chain은 node별로 buffer가 다를 수 있다. clone은 각 node를 개별 clone해 각 buffer의 refcount를 늘린다.
auto chain = makeThreeNodeChain();auto cloned = chain->clone();// 3개 node 모두 새로 만들고, 각각 자기 buffer의 refcount 증가unshareChain()은 chain의 모든 node를 unshare한다.
chain->unshareChain(); // 모든 node 자기 buffer로 분리#안전 규칙
- shared buffer에 write 금지.
isShared()또는unshare()후 write. - wrapBuffer는 lifetime을 caller가 보장. heap/stack 구분.
- takeOwnership의 free callback이 thread-safe 한지 확인. ref-count가 어느 thread에서 0이 될지 모름.
- clone 후 chain pointer를 caller에 노출하면 안 됨. clone은 새 chain이지만 같은 buffer다.
#코드 리뷰 포인트
writableData()호출 전isShared()체크? shared면 silent corruption.takeOwnership의 free callback이 다른 destructor와 race하지 않는가? atomic decrement 후 호출됨.wrapBuffer의 lifetime이 명확한가? 같은 함수 안에서 사용/소멸이 보이는가.- chain 전체를 clone하는데 외부에서는 node 하나만 본다고 가정하지 않는가? clone vs cloneOne 구분.
#자주 보는 안티패턴
// 1. clone 후 mutationauto b = a->clone();b->writableData()[0] = 'x'; // a도 바뀜// 옳음:b->unshare();b->writableData()[0] = 'x';
// 2. wrapBuffer + temporaryauto buf = folly::IOBuf::wrapBuffer(makeTempString().data(), 5);// makeTempString() 소멸 — buf dangling
// 3. takeOwnership에서 다른 IOBuf와 share된 메모리auto buf1 = folly::IOBuf::create(1024);auto buf2 = folly::IOBuf::takeOwnership( buf1->writableData(), 100, // buf1과 same buffer [](void*, void*) { /* nothing */ });// buf1 또는 buf2 destroy 시 double free 또는 use-after-free
// 4. 다른 thread에서 unshare 도중 read// thread 1: buf->unshareOne(); // 새 buffer 할당 중// thread 2: read(buf->data()); // race// IOBuf의 unshare는 thread-safe 아니다 — node 단위 sync 필요#std::shared_ptr와 비교
std::shared_ptr<T>는 T 전체를 ref-count 관리한다. IOBuf의 clone은 buffer를 share하지만 node는 독립이다.
| 항목 | std::shared_ptr | folly::IOBuf clone |
|---|---|---|
| 공유 단위 | 전체 객체 | buffer만 |
| ref-count 위치 | control block | SharedInfo |
| 분리 | 항상 deep copy | unshare로 buffer만 copy |
| 분기 view | weak_ptr/aliasing constructor | 자연스러움 |
shared_ptr<T> + aliasing constructor로 비슷한 모양을 만들 수 있지만 IOBuf는 chain까지 표현해 더 풍부하다.
#정리
- IOBuf의 node와 buffer는 별개다. node는 chain의 link, buffer는 byte 영역.
clone은 buffer를 share하고 새 node를 만든다(얕은 복사).unshare는 buffer를 자기만의 copy로 분리한다(write 전 안전).takeOwnership은 외부 메모리를 ref-count로 관리한다.wrapBuffer는 zero-cost wrap이지만 lifetime은 caller 책임.SharedInfo.refcount는 atomic. 외부 참조는externallyShared비트로 표시.- shared buffer에 write 금지. 항상
isShared/unshare후 write.
#다음 편
Part 5부터 String/Format을 본다. 이 시리즈의 Part 1-4가 Folly의 async + I/O 핵심을 다뤘다.
#관련 항목
Folly Code Review · 23 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 Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
IOBuf chain을 직접 writev/readv에 넘기고, splice/sendfile과 결합해 zero-copy 송수신 파이프라인을 구성한다.
같은 시리즈에서 이어 읽기
folly::io::Cursor·RWCursor — chain 위의 stream
Cursor는 IOBuf chain을 단일 stream처럼 읽고 쓰는 추상화. endian-safe primitive read와 chain 자동 순회를 제공한다.
같은 시리즈에서 이어 읽기
folly::IOBufQueue — chain의 push/pull 추상화
IOBufQueue는 IOBuf chain의 append/prepend/split을 효율적으로 관리한다. streaming codec과 framing layer의 표준 도구다.
같은 시리즈에서 이어 읽기