Pin
Async blocks and functions return types implementing the Future
trait. The type returned is the result of a compiler transformation which turns local variables into data stored inside the future.
Some of those variables can hold pointers to other local variables. Because of that, the future should never be moved to a different memory location, as it would invalidate those pointers.
To prevent moving the future type in memory, it can only be polled through a pinned pointer. Pin
is a wrapper around a reference that disallows all operations that would move the instance it points to into a different memory location.
Speaker Notes
-
위에서 소개한 것은 액터(actor) 패턴의 한 예라고 봐도 무방합니다. 액터는 일반적으로 루프 안에서
select!
를 호출합니다. -
이전 강의 몇 개의 내용을 요약한 것이기 때문에 천천히 살펴보세요.
-
_ = sleep(Duration::from_millis(100)) => { println!(..) }
을select!
에 추가해 보세요. 이 작업은 실행되지 않습니다. 왜 그럴까요? -
대신, 해당 future가 포함된
timeout_fut
를loop
외부에 추가해 보세요. -
여전히 작동하지 않습니다. 컴파일러 오류를 따라
select!
의timeout_fut
에&mut
를 추가하여 Move 시멘틱 관련한 문제를 해결하고Box::pin
을 사용하세요. -
이는 컴파일은 되지만 타임 아웃이 되면 매번 반복할 때 마다
Poll::Ready
가 됩니다(융합된 future가 도움이 될 수 있음). 타임 아웃 될 때마다timeout_fut
를 리셋하도록 수정하세요.
-
-
Box는 힙에 할당합니다. 경우에 따라
std::pin::pin!
(최근에야 안정화되었으며 이전 코드는tokio::pin!
을 사용하는 경우가 많음)도 사용할 수 있지만 이는 재할당된 future에 사용하기가 어렵습니다. -
또 다른 방법은
pin
을 아예 사용하지 않고 100ms마다oneshot
채널에 전송할 다른 작업을 생성하는 것입니다. -
Data that contains pointers to itself is called self-referential. Normally, the Rust borrow checker would prevent self-referential data from being moved, as the references cannot outlive the data they point to. However, the code transformation for async blocks and functions is not verified by the borrow checker.
-
Pin
is a wrapper around a reference. An object cannot be moved from its place using a pinned pointer. However, it can still be moved through an unpinned pointer. -
The
poll
method of theFuture
trait usesPin<&mut Self>
instead of&mut Self
to refer to the instance. That’s why it can only be called on a pinned pointer.