연결 리스트를 enum 으로 그대로 쓰면 recursive type has infinite size 로 컴파일되지 않는다. 같은 리스트를 두 곳에서 꼬리로 쓰려 하면 E0382 가, 공유한 값을 바꾸려 하면 E0596 이, 그 값을 스레드로 넘기면 E0277 이 난다. 이 에러들은 두 가지 제약에서 나온다. 하나는 스택에 둘 값의 크기가 컴파일 시점에 정해져야 한다는 것이다. 다른 하나는 소유권 글부터 이어 온 규칙이다. 값마다 소유자는 하나이고, 참조는 공유 참조 여럿 또는 가변 참조 하나만 동시에 있을 수 있으며, 컴파일러가 이 규칙을 검사한다.

스마트 포인터는 포인터처럼 역참조할 수 있고(Deref), 스코프를 벗어날 때 정리 작업을 하는(Drop) 타입이다. 크기 제약은 값을 힙에 두는 Box 가 푼다. 소유·대여 규칙은 Rc 가 소유자를 여럿 두고, RefCell 이 대여 검사를 런타임으로 미루고, Arc·Mutex 가 같은 일을 스레드 사이에서 하는 방식으로 넓힌다. 공짜는 아니다. 힙 할당, 카운트 증감, 런타임 panic, 잠금 대기를 대신 치른다. 아래 예제는 모두 rustc 1.94.1, edition 2021 에서 컴파일하고 aarch64-apple-darwin(Apple Silicon macOS)에서 실행했다. 크기는 64비트 타깃 기준이다.

Box — 값은 힙에, 소유자는 하나

Box 는 스택에 포인터만 두고 값은 힙에 둔다. Box<dyn Trait> 는 vtable 포인터를 하나 더 갖는다스택n: Box<i32>포인터 8Bshape: Box<dyn Shape>데이터 포인터 8Bvtable 포인터 8B힙5Square(2.0)vtable (정적 영역)Square::areaBox 를 drop 하면 가리키던 힙 값도 함께 해제된다

Box<T> 는 T 를 힙에 할당하고 그 주소를 스택에 둔다. 소유 규칙은 일반 값과 같다. 소유자는 하나이고, 대입하면 이동하고, 소유자가 사라지면 힙 값도 해제된다.

use std::mem::size_of;

struct Noisy(&'static str);

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("drop {}", self.0);
    }
}

fn main() {
    println!("Box<i32>      = {} bytes", size_of::<Box<i32>>());
    println!("Box<[u8; 1024]> = {} bytes", size_of::<Box<[u8; 1024]>>());

    let n = Box::new(5);
    println!("*n + 1 = {}", *n + 1);

    let a = Box::new(Noisy("a"));
    let b = a;
    println!("moved a into b");
    drop(b);
    println!("end of main");
}
Box<i32>      = 8 bytes
Box<[u8; 1024]> = 8 bytes
*n + 1 = 6
moved a into b
drop a
end of main

i32 를 담든 1024바이트 배열을 담든 Box 자체는 포인터 하나인 8바이트다. Box 가 Deref 를 구현하므로 *n 으로 역참조하면 힙의 값을 일반 값처럼 쓴다. a 를 b 로 옮길 때 복사되는 것은 포인터 8바이트뿐이고, drop(b) 에서 Noisy 의 Drop 이 한 번 불렸다. end of main 보다 먼저 찍혔으니 해제 시점은 b 가 사라진 순간이다. Box 의 Drop 이 안의 값을 drop 하고 힙 메모리를 돌려준다.

여기까지는 값을 굳이 힙에 둘 이유가 보이지 않는다. 그림 아래쪽의 shape 와 다음 절의 재귀 타입처럼, 크기를 컴파일 시점에 정할 수 없는 값에서 그 이유가 드러난다.

재귀 타입 — 크기를 정하려면 포인터가 필요하다

Box 없는 재귀 enum 은 크기가 무한하고, Box 를 넣으면 노드마다 16바이트로 정해진다Box 없이 — 크기를 끝없이 더한다i32i32i32…E0072: recursive type `List` has infinite sizeBox 로 — Cons 하나는 16바이트Cons(1, Box)Cons(2, Box)Nil스택힙힙포인터 크기는 정해져 있어 List 크기가 유한해진다

컴파일러는 스택에 값을 두려고 타입마다 크기를 컴파일 시점에 계산한다. 자기 자신을 필드로 가진 enum 은 이 계산이 끝나지 않는다.

enum List {
    Cons(i32, List),
    Nil,
}

fn main() {
    let _list = List::Cons(1, List::Nil);
}
error[E0072]: recursive type `List` has infinite size
 --> list_err.rs:1:1
  |
1 | enum List {
  | ^^^^^^^^^
2 |     Cons(i32, List),
  |               ---- recursive without indirection
  |
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle
  |
2 |     Cons(i32, Box<List>),
  |               ++++    +

같은 원인에서 나온 E0391(List 의 drop 필요 여부 계산이 순환한다)도 함께 출력됐는데 생략했다. Cons 의 크기는 i32 더하기 List 이고, 그 List 가 다시 i32 더하기 List 다. 컴파일러 제안대로 Box<List> 로 바꾸면 Cons 가 담는 것은 포인터가 된다.

use std::mem::size_of;

enum List {
    Cons(i32, Box<List>),
    Nil,
}

use List::{Cons, Nil};

fn sum(list: &List) -> i32 {
    match list {
        Cons(value, rest) => value + sum(rest),
        Nil => 0,
    }
}

fn main() {
    let list = Cons(1, Box::new(Cons(2, Box::new(Nil))));
    println!("sum = {}", sum(&list));
    println!("List = {} bytes", size_of::<List>());
}
sum = 3
List = 16 bytes

List 는 16바이트가 됐다. i32 와 포인터가 들어가는 크기이고, Cons 와 Nil 을 어떻게 구분하는지를 포함한 배치는 다음 글에서 본다. 노드가 몇 개든 List 하나의 크기는 그대로이고, 다음 노드는 힙에 있다.

Box<dyn Trait> — 크기가 다른 타입을 한 Vec 에

trait·제네릭·dyn 글에서 dyn Trait 는 크기를 컴파일 시점에 알 수 없어 & 나 Box 같은 포인터를 거쳐 다룬다고 했고, Box<dyn Shape> 가 16바이트인 것도 거기서 확인했다. 이 글에서 볼 것은 소유다. &dyn Trait 는 빌린 값만 가리키지만 Box<dyn Trait> 는 값을 소유한다. 타입이 다른 값을 한 Vec 에 담고, 그 Vec 이 원소를 해제하게 할 때 쓴다.

trait Shape {
    fn area(&self) -> f64;
}

struct Square(f64);
struct Circle(f64);

impl Shape for Square {
    fn area(&self) -> f64 {
        self.0 * self.0
    }
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        3.14 * self.0 * self.0
    }
}

impl Drop for Square {
    fn drop(&mut self) {
        println!("drop Square");
    }
}

impl Drop for Circle {
    fn drop(&mut self) {
        println!("drop Circle");
    }
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0)), Box::new(Circle(1.0))];
    let total: f64 = shapes.iter().map(|shape| shape.area()).sum();
    println!("total = {total:.2}");
    drop(shapes);
    println!("end of main");
}
total = 7.14
drop Square
drop Circle
end of main

drop(shapes) 한 번에 Square 와 Circle 의 Drop 이 차례로 불렸다. Vec 은 Box<dyn Shape> 원소를 하나씩 drop 하고, 각 Box 는 vtable 에 든 drop 함수로 실제 타입의 Drop 을 부른 뒤 힙 메모리를 돌려준다. 첫 그림의 shape 가 이 데이터 포인터와 vtable 포인터다.

Rc — 소유자를 여럿 두기

Box 의 소유자는 하나라서, 같은 리스트를 두 리스트의 꼬리로 쓰려고 하면 두 번째 사용에서 컴파일 에러가 난다.

#[derive(Debug)]
enum List {
    Cons(i32, Box<List>),
    Nil,
}

use List::{Cons, Nil};

fn main() {
    let shared = Cons(5, Box::new(Cons(10, Box::new(Nil))));
    let b = Cons(3, Box::new(shared));
    let c = Cons(4, Box::new(shared));
    println!("{b:?} {c:?}");
}
error[E0382]: use of moved value: `shared`
  --> box_share_err.rs:12:30
   |
10 |     let shared = Cons(5, Box::new(Cons(10, Box::new(Nil))));
   |         ------ move occurs because `shared` has type `List`, which does not implement the `Copy` trait
11 |     let b = Cons(3, Box::new(shared));
   |                              ------ value moved here
12 |     let c = Cons(4, Box::new(shared));
   |                              ^^^^^^ value used here after move
   |
note: if `List` implemented `Clone`, you could clone the value
  --> box_share_err.rs:2:1
   |
 2 | enum List {
   | ^^^^^^^^^ consider implementing `Clone` for this type
...
11 |     let b = Cons(3, Box::new(shared));
   |                              ------ you could clone this value

컴파일러는 Clone 을 제안하지만, 그러면 리스트가 두 벌이 된다. 한 벌을 둘이 함께 소유하려면 참조 횟수를 세는 Rc<T>(Reference Counted)를 쓴다.

세 값이 Rc 할당 하나를 가리키고 strong 이 3 이다sharedb: Cons(3, ●)c: Cons(4, ●)Rc 를 가진 값힙 · Rc 할당 하나strong 3weak 0Cons(5, ●)Rc::clone 은 값을 복사하지 않고 strong 만 1 올린다
use std::rc::Rc;

enum List {
    Cons(i32, Rc<List>),
    Nil,
}

use List::{Cons, Nil};

fn sum(list: &List) -> i32 {
    match list {
        Cons(value, rest) => value + sum(rest),
        Nil => 0,
    }
}

fn main() {
    let shared = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
    let b = Cons(3, Rc::clone(&shared));
    let c = Cons(4, Rc::clone(&shared));
    println!("b = {}, c = {}", sum(&b), sum(&c));
    println!("shared strong = {}", Rc::strong_count(&shared));
}
b = 18, c = 19
shared strong = 3

Rc::new 는 값과 함께 카운트 두 개를 힙에 할당한다. 값을 소유하는 Rc 의 수인 strong 카운트와, 뒤에서 볼 Weak 의 수인 weak 카운트다. Rc::clone 은 값을 복사하지 않고 strong 카운트를 1 늘린 포인터를 하나 더 만든다. shared, b 안의 Rc, c 안의 Rc 셋이 같은 할당을 가리켜 strong 카운트가 3 이다. shared.clone() 으로 써도 같은 일을 하지만, 깊은 복사가 아니라는 것이 보이도록 Rc::clone(&shared) 형태를 썼다.

Rc::clone 마다 strong 이 오르고 drop 마다 내려가며, 0 이 되면 값이 해제된다코드strong countlet a = Rc::new(..)1let b = Rc::clone(&a)2let c = Rc::clone(&a)3} // c 스코프 끝2drop(a)1drop(b)0 → 값 dropdrop config 은 마지막 Rc 가 사라질 때 한 번 찍힌다

strong 카운트가 언제 줄고 값이 언제 해제되는지 Drop 출력으로 확인했다.

use std::rc::Rc;

struct Noisy(&'static str);

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("drop {}", self.0);
    }
}

fn main() {
    let a = Rc::new(Noisy("config"));
    println!("after a: strong = {}", Rc::strong_count(&a));

    let b = Rc::clone(&a);
    println!("after b: strong = {}", Rc::strong_count(&a));

    {
        let c = Rc::clone(&a);
        println!("after c: strong = {}", Rc::strong_count(&c));
    }
    println!("c dropped: strong = {}", Rc::strong_count(&a));

    println!("same allocation = {}", Rc::ptr_eq(&a, &b));
    drop(a);
    println!("a dropped: strong = {}", Rc::strong_count(&b));
    drop(b);
    println!("end of main");
}
after a: strong = 1
after b: strong = 2
after c: strong = 3
c dropped: strong = 2
same allocation = true
a dropped: strong = 1
drop config
end of main

c 가 스코프를 벗어나도, a 를 먼저 drop 해도 값은 남아 있다. drop config 는 마지막 소유자 b 가 사라져 strong 카운트가 0 이 될 때 한 번 찍혔다. 소유자는 셋으로 늘었지만 해제는 여전히 정확히 한 번이다. 바뀐 것은 해제 시점을 정하는 쪽이다. 컴파일러가 스코프로 정하던 것을 카운트가 실행 중에 정한다.

RefCell — 공유한 값을 바꾸기

Rc 가 주는 것은 공유 참조뿐이다. 소유자가 여럿인 값을 그중 하나가 바꾸게 하면 대여 규칙이 깨지므로, 소유자가 여럿인 동안 Rc 로는 &mut T 를 얻을 수 없다.

use std::rc::Rc;

fn main() {
    let shared = Rc::new(vec![1, 2]);
    let other = Rc::clone(&shared);
    other.push(3);
    println!("{shared:?}");
}
error[E0596]: cannot borrow data in an `Rc` as mutable
 --> rc_mut_err.rs:6:5
  |
6 |     other.push(3);
  |     ^^^^^ cannot borrow as mutable
  |
  = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Vec<i32>>`

RefCell<T> 는 공유 참조 &RefCell<T> 로도 안의 값을 바꾸게 해 준다. 내부 가변성(interior mutability)이라고 부른다. 대여 규칙을 없애는 것이 아니라, 검사를 컴파일 시점에서 런타임으로 옮긴다.

RefCell 은 공유 대여 여럿 또는 가변 대여 하나만 허용하고, 겹치면 런타임에 panic 한다대여 상태호출결과대여 없음borrow()공유 대여 1공유 대여 nborrow()공유 대여 n+1대여 없음borrow_mut()가변 대여 1공유 대여 nborrow_mut()panic가변 대여 1borrow()panicRef·RefMut 가 drop 되면 대여가 풀린다try_borrow_mut() 는 panic 대신 Err 를 돌려준다

borrow() 는 공유 대여 Ref 를, borrow_mut() 는 가변 대여 RefMut 를 돌려준다. RefCell 은 지금 공유 대여가 몇 개인지, 가변 대여가 있는지를 대여 상태로 기록해 두고, 호출마다 이 상태를 확인한다.

use std::cell::RefCell;
use std::rc::Rc;

fn main() {
    let log = Rc::new(RefCell::new(Vec::new()));
    let writer = Rc::clone(&log);

    writer.borrow_mut().push("start");
    writer.borrow_mut().push("stop");

    {
        let first = log.borrow();
        let second = log.borrow();
        println!("readers: {first:?} {second:?}");
        println!("borrow_mut while reading: {}", log.try_borrow_mut().is_err());
    }
    println!("borrow_mut after readers: {}", log.try_borrow_mut().is_ok());
}
readers: ["start", "stop"] ["start", "stop"]
borrow_mut while reading: true
borrow_mut after readers: true

writer 로 넣은 값이 log 에서 보인다. Rc<RefCell<T>> 는 소유자 여럿이 같은 값을 바꿀 수 있게 하는 조합이다. first·second 가 살아 있는 동안 try_borrow_mut 는 Err 를 돌려줬고, 블록을 벗어나 둘이 drop 된 뒤에는 Ok 가 됐다. writer.borrow_mut() 두 줄이 충돌하지 않은 것도 같은 이유다. 각 RefMut 는 그 문장이 끝날 때 drop 된다.

try_ 없이 겹치게 빌리면 컴파일은 통과하고 실행 중에 panic 한다.

use std::cell::RefCell;

fn main() {
    let names = RefCell::new(vec![String::from("a")]);
    let first = names.borrow();
    names.borrow_mut().push(String::from("b"));
    println!("{first:?}");
}

thread 'main' (59900242) panicked at refcell_panic.rs:6:11:
RefCell already borrowed
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

괄호 안 숫자는 스레드 ID 라 실행마다 다르다. 같은 코드를 Vec 과 일반 참조로 쓰면 참조와 borrow 글의 E0502 로 컴파일러가 거부한다. RefCell 은 그 에러를 panic 으로 바꿨다. 컴파일러가 증명할 수 없는 패턴을 허용하는 대신, 증명하지 못한 부분은 실행할 때 확인한다. 대여 상태를 저장하고 호출마다 확인하는 비용이 든다.

순환 참조 — Rc 로 만든 누수

두 노드가 서로를 Rc 로 가리키면 변수를 drop 해도 strong 이 1 로 남아 누수된다drop 전노드 a · strong 2노드 b · strong 2nextnextabdrop(a); drop(b) 이후노드 a · strong 1노드 b · strong 1nextnext가리키는 변수가없다서로의 strong 이 1 로 남아 Drop 이 한 번도 불리지 않는다

Rc<RefCell<T>> 를 쓰면 값끼리 서로를 가리키게 만들 수 있다. 두 노드가 서로를 Rc 로 가리키면 strong 카운트가 0 이 되지 않는다.

use std::cell::RefCell;
use std::rc::Rc;

struct Node {
    name: &'static str,
    next: RefCell<Option<Rc<Node>>>,
}

impl Drop for Node {
    fn drop(&mut self) {
        println!("drop {}", self.name);
    }
}

fn main() {
    let a = Rc::new(Node { name: "a", next: RefCell::new(None) });
    let b = Rc::new(Node { name: "b", next: RefCell::new(Some(Rc::clone(&a))) });
    *a.next.borrow_mut() = Some(Rc::clone(&b));

    let watch_a = Rc::downgrade(&a);
    let watch_b = Rc::downgrade(&b);

    println!("a strong = {}, b strong = {}", Rc::strong_count(&a), Rc::strong_count(&b));
    drop(a);
    drop(b);
    println!("after drop: a strong = {}, b strong = {}", watch_a.strong_count(), watch_b.strong_count());
    println!("end of main");
}
a strong = 2, b strong = 2
after drop: a strong = 1, b strong = 1
end of main

drop a·drop b 는 끝까지 찍히지 않았다. 변수 a 와 b 를 drop 한 뒤 미리 만들어 둔 Weak 로 확인하니 strong 카운트가 각각 1 이었다. 남은 1 은 상대 노드의 next 가 가지고 있다. 두 노드 모두 프로그램 어디에서도 접근할 수 없는데 해제되지 않는다. 메모리 누수다. 프로세스가 끝나면 운영체제가 메모리를 회수하므로, 실행 중에 쌓이는 누수다.

이 코드에 unsafe 는 없다. Rust Book 은 누수 방지를 Rust 의 보장 범위 밖이라 적고, 누수는 메모리 안전하다고 한다. 해제된 메모리를 읽는 일은 일어나지 않고, 해제가 일어나지 않을 뿐이다. 해제 시점을 카운트에 맡기면 순환을 만들지 않을 책임은 코드를 쓰는 쪽으로 넘어온다고 봤다.

Weak — strong 카운트를 늘리지 않는 참조

자식은 Rc, 부모는 Weak 로 가리키면 branch 가 스코프를 벗어날 때 해제된다branch 스코프 안branchleafbranchstrong 1 · weak 1leafstrong 2 · weak 0children: Rcparent: Weakbranch 스코프 끝branch 해제됨leafleafstrong 1 · weak 0upgrade() → NoneWeak 는 strong 을 올리지 않아 순환이 생기지 않는다

순환을 끊으려면 한쪽 방향을 소유하지 않는 참조로 바꾼다. Rc::downgrade 는 strong 카운트 대신 weak 카운트를 늘린 Weak<T> 를 만든다. Weak 는 값을 살려 두지 않는다. 값에 접근하려면 upgrade() 로 Option<Rc<T>> 를 받아야 하고, 값이 이미 해제됐으면 None 이 나온다. 트리에서 부모는 자식을 소유하고, 자식은 부모를 Weak 로 가리키는 식이다.

use std::cell::RefCell;
use std::rc::{Rc, Weak};

struct Node {
    name: &'static str,
    parent: RefCell<Weak<Node>>,
    children: RefCell<Vec<Rc<Node>>>,
}

impl Drop for Node {
    fn drop(&mut self) {
        println!("drop {}", self.name);
    }
}

fn main() {
    let leaf = Rc::new(Node {
        name: "leaf",
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![]),
    });
    println!("leaf parent = {:?}", leaf.parent.borrow().upgrade().map(|p| p.name));

    {
        let branch = Rc::new(Node {
            name: "branch",
            parent: RefCell::new(Weak::new()),
            children: RefCell::new(vec![Rc::clone(&leaf)]),
        });
        *leaf.parent.borrow_mut() = Rc::downgrade(&branch);

        println!("leaf parent = {:?}", leaf.parent.borrow().upgrade().map(|p| p.name));
        println!("branch children = {}", branch.children.borrow().len());
        println!("branch strong = {}, weak = {}", Rc::strong_count(&branch), Rc::weak_count(&branch));
        println!("leaf   strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf));
    }

    println!("leaf parent = {:?}", leaf.parent.borrow().upgrade().map(|p| p.name));
    println!("leaf   strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf));
}
leaf parent = None
leaf parent = Some("branch")
branch children = 1
branch strong = 1, weak = 1
leaf   strong = 2, weak = 0
drop branch
leaf parent = None
leaf   strong = 1, weak = 0
drop leaf

블록 안에서 branch 는 strong 카운트 1(변수 branch)에 weak 카운트 1(leaf.parent)이고, leaf 는 strong 카운트 2(변수 leaf 와 branch.children)다. 블록이 끝나자 branch 의 strong 카운트가 0 이 되어 drop branch 가 찍혔다. weak 카운트 1 이 남아 있었지만 해제는 그대로 일어났다. 그 뒤 upgrade() 는 None 을 돌려줬고, branch.children 이 사라지면서 leaf 의 strong 카운트도 1 로 줄었다. 순환 참조 예제와 달리 main 이 끝나면서 drop leaf 까지 찍혔다.

Arc 와 Mutex — 스레드 사이의 공유

Rc 와 Arc<RefCell> 은 스레드로 넘길 수 없고 Arc<Mutex> 는 넘길 수 있다캡처한 타입thread::spawn 결과Rc<i32>spawn컴파일 에러 E0277Rc 는 Send 아님Arc<RefCell<i32>>spawn컴파일 에러 E0277RefCell 은 Sync 아님Arc<Mutex<i32>>spawn컴파일됨Mutex 가 Sync 를 준다Send — 값을 다른 스레드로 옮겨도 된다Sync — 여러 스레드가 &T 를 함께 가져도 된다

Rc 를 스레드로 넘기면 컴파일되지 않는다.

use std::rc::Rc;
use std::thread;

fn main() {
    let counter = Rc::new(0);
    let handle = thread::spawn(move || {
        println!("{counter}");
    });
    handle.join().unwrap();
}
error[E0277]: `Rc<i32>` cannot be sent between threads safely
   --> rc_thread_err.rs:6:32
    |
  6 |       let handle = thread::spawn(move || {
    |                    ------------- ^------
    |                    |             |
    |  __________________|_____________within this `{closure@rc_thread_err.rs:6:32: 6:39}`
    | |                  |
    | |                  required by a bound introduced by this call
  7 | |         println!("{counter}");
  8 | |     });
    | |_____^ `Rc<i32>` cannot be sent between threads safely
    |
    = help: within `{closure@rc_thread_err.rs:6:32: 6:39}`, the trait `Send` is not implemented for `Rc<i32>`
note: required because it's used within this closure
   --> rc_thread_err.rs:6:32
    |
  6 |     let handle = thread::spawn(move || {
    |                                ^^^^^^^
note: required by a bound in `spawn`
   --> …/library/std/src/thread/functions.rs:128:8
    |
125 | pub fn spawn<F, T>(f: F) -> JoinHandle<T>
    |        ----- required by a bound in this function
...
128 |     F: Send + 'static,
    |        ^^^^ required by this bound in `spawn`

표준 라이브러리 경로는 줄였다. thread::spawn 은 클로저에 Send bound 를 건다. Send 는 값을 다른 스레드로 옮겨도 된다는 표시이고, 클로저 필드가 모두 Send 여야 클로저도 Send 다. std 문서는 Rc 가 원자적이지 않은 카운트를 써서 비용은 낮지만 스레드 사이로 보낼 수 없고, 그래서 Send 를 구현하지 않는다고 적는다. 두 스레드가 같은 카운트를 동시에 늘리면 증가 하나가 사라질 수 있다.

스레드 사이에서는 Arc<T>(Atomically Reference Counted)를 쓴다. 카운트를 원자적(atomic) 연산으로 갱신하고, 나머지 쓰임은 Rc 와 같다. 그런데 Arc 도 주는 것은 공유 참조뿐이라, 값을 바꾸려면 내부 가변성이 필요하다. RefCell 을 넣으면 다시 컴파일되지 않는다.

use std::cell::RefCell;
use std::sync::Arc;
use std::thread;

fn main() {
    let counter = Arc::new(RefCell::new(0));
    let worker = Arc::clone(&counter);
    let handle = thread::spawn(move || {
        *worker.borrow_mut() += 1;
    });
    handle.join().unwrap();
}
error[E0277]: `RefCell<i32>` cannot be shared between threads safely
   --> arc_refcell_err.rs:8:32
    |
  8 |       let handle = thread::spawn(move || {
    |  __________________-------------_^
    | |                  |
    | |                  required by a bound introduced by this call
  9 | |         *worker.borrow_mut() += 1;
 10 | |     });
    | |_____^ `RefCell<i32>` cannot be shared between threads safely
    |
    = help: the trait `Sync` is not implemented for `RefCell<i32>`
    = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead
    = note: required for `Arc<RefCell<i32>>` to implement `Send`
note: required because it's used within this closure
   --> arc_refcell_err.rs:8:32
    |
  8 |     let handle = thread::spawn(move || {
    |                                ^^^^^^^
note: required by a bound in `spawn`
   --> …/library/std/src/thread/functions.rs:128:8
    |
125 | pub fn spawn<F, T>(f: F) -> JoinHandle<T>
    |        ----- required by a bound in this function
...
128 |     F: Send + 'static,
    |        ^^^^ required by this bound in `spawn`

이번에 빠진 것은 Sync 다. std 문서의 정의로 T 가 Sync 이면 &T 가 Send 다. 여러 스레드가 &T 를 함께 가져도 된다는 뜻이다. Arc<T> 는 T 가 Send 이고 Sync 일 때만 Send 다. RefCell 은 안의 값이 Send 면 Send 라서 통째로 다른 스레드로 옮길 수는 있다. 하지만 대여 상태가 한 스레드에서만 맞게 갱신되므로 Sync 가 아니다. 에러의 두 번째 note 가 이 연결을 보여 준다. 컴파일러가 제안한 RwLock 도 되지만, 여기서는 Mutex<T> 를 쓴다.

main 과 스레드 넷이 Arc 할당 하나를 공유하고 Mutex 가 한 번에 한 스레드만 값을 바꾸게 한다Arc 를 가진 쪽main스레드 1스레드 2스레드 3스레드 4힙 · Arc 할당 하나strong · atomic 증감잠금 · 한 번에 하나값 0 → 4000lock() 이 돌려준 MutexGuard 가 drop 되면 잠금이 풀린다
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = Vec::new();

    for _ in 0..4 {
        let counter = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            for _ in 0..1000 {
                *counter.lock().unwrap() += 1;
            }
        }));
    }

    for handle in handles {
        handle.join().unwrap();
    }
    println!("strong after join = {}", Arc::strong_count(&counter));
    println!("counter = {}", *counter.lock().unwrap());
}
strong after join = 1
counter = 4000

스레드 넷이 1000번씩 더해 4000 이 나왔다. 각 스레드는 Arc::clone 으로 받은 자기 counter 를 move 로 가져갔고, 스레드가 끝나며 그 Arc 가 drop 되어 join 뒤 strong 카운트는 1 이다. lock() 은 다른 스레드가 잠금을 가지고 있으면 풀릴 때까지 기다렸다가 MutexGuard 를 돌려준다. 이 guard 가 RefMut 와 같은 역할을 하고, drop 되면 잠금이 풀린다. RefCell 이 겹친 대여를 panic 으로 거부했다면 Mutex 는 기다리게 한다. 기다림에도 비용이 있다. std 문서는 잠금을 가진 스레드가 다시 lock() 을 부르면 그 호출이 돌아오지 않는다고(deadlock 이나 panic) 적는다. unwrap() 은 잠금을 가진 스레드가 panic 했을 때 돌아오는 에러를 처리하는데, 이 글에서는 다루지 않는다.

Mutex<T> 는 T 가 Send 이기만 하면 Sync 다. 잠금이 한 번에 한 스레드만 값에 접근하게 하기 때문이다. 그래서 Arc<Mutex<i32>> 는 Send 가 되고 spawn 을 통과한다. Rc·RefCell 이 하던 일을 Arc·Mutex 가 스레드 사이에서 하고, 원자적 연산과 잠금 대기를 대가로 치른다.

포인터 선택 기준

필요한 것에 따라 Box, Rc, RefCell, Arc, Mutex 를 고르고 각각 검사 시점과 비용이 다르다필요한 것포인터대여 검사비용힙 · 재귀 타입 · dynBox<T>컴파일할당 1회한 스레드, 소유자 여럿Rc<T>컴파일카운트 ±1공유한 값 바꾸기RefCell<T>런타임대여 상태스레드 사이 소유자 여럿Arc<T>컴파일atomic ±1스레드 사이 값 바꾸기Mutex<T>런타임잠금

다섯 타입은 무엇을 푸는지가 각자 다르다. Box 는 소유·대여 규칙을 그대로 두고 크기 제약만 푼다. Rc·Arc 는 소유자를 여럿으로 늘리고 해제 시점을 카운트에 맡긴다. RefCell·Mutex 는 대여 규칙은 지키되 검사를 런타임으로 미룬다. 스레드 사이로 넘어가야 하면 Rc 는 Arc 로, RefCell 은 Mutex 로 바뀐다.

고르는 순서는 이렇게 봤다. 일반 값과 참조로 충분하면 그대로 쓴다. 크기가 문제면 Box 를 쓴다. 소유자 여럿이나 공유 중 변경이 꼭 필요할 때만 Rc·RefCell 을 쓰고, 스레드를 건너야 할 때만 Arc·Mutex 로 바꾼다. 뒤로 갈수록 실행 중에 치르는 비용이 늘어난다.

마무리

소유자가 늘고 검사가 런타임으로 옮겨 가도 지켜진 것이 있다. Rc 로 소유자가 셋이 됐지만 drop config 는 한 번만 찍혔고, RefCell 은 겹친 대여를 여전히 거부했다. 컴파일러 대신 RefCell already borrowed panic 이 거부했을 뿐이다. 달라진 것은 검사하는 시점과 그 비용이다. 해제 시점을 카운트에 맡긴 Rc 는 순환 참조에서 끝내 해제되지 않았고, 컴파일러가 잡지 않는 그 부분은 Weak 로 직접 끊어야 했다. 다음 글에서는 이 글에서 미룬 것, Rc·RefCell·Mutex 같은 래퍼의 크기와 List 처럼 enum 이 메모리에 놓이는 방식을 본다.

참고