Update some broken anchor links (#1444)

This commit is contained in:
Philipp Oppermann
2025-12-08 17:31:52 +01:00
committed by GitHub
parent 86c36479cf
commit 211f460251
56 changed files with 387 additions and 387 deletions

View File

@@ -125,7 +125,7 @@ pub trait Future {
}
```
El tipo [asociado](https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types) `Output` especifica el tipo del valor asíncrono. Por ejemplo, la función `async_read_file` en el diagrama anterior devolvería una instancia de `Future` con `Output` configurado a `File`.
El tipo [asociado](https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#associated-types) `Output` especifica el tipo del valor asíncrono. Por ejemplo, la función `async_read_file` en el diagrama anterior devolvería una instancia de `Future` con `Output` configurado a `File`.
El método [`poll`] permite comprobar si el valor ya está disponible. Devuelve un enum [`Poll`], que se ve de la siguiente manera:
@@ -807,7 +807,7 @@ La estructura `Task` es un envoltorio nuevo alrededor de un futuro pinzado, asig
- Como aprendimos en la [sección sobre pinning], el tipo `Pin<Box>` asegura que un valor no puede moverse en memoria al colocarlo en el heap y prevenir la creación de referencias `&mut` a él. Esto es importante porque los futuros generados por async/await podrían ser auto-referenciales, es decir, contener punteros a sí mismos que se invalidarían cuando el futuro se moviera.
[_trait object_]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html
[_despachados dinámicamente_]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#trait-objects-perform-dynamic-dispatch
[_despachados dinámicamente_]: https://doc.rust-lang.org/book/ch18-02-trait-objects.html#trait-objects-perform-dynamic-dispatch
[sección sobre pinning]: #pinning
Para permitir la creación de nuevas estructuras `Task` a partir de futuros, creamos una función `new`:

View File

@@ -130,7 +130,7 @@ pub trait Future {
[関連型] `Output` は非同期値の型を指定します。例えば、上の図の `async_read_file` 関数は、`Output``File` に設定した `Future` インスタンスを返します。
[関連型]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types
[関連型]: https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#associated-types
[`poll`]メソッドは、その値がすでに利用可能かどうかをチェックすることができます。このメソッドは、以下のような [`Poll`] 列挙体を返します。
@@ -818,7 +818,7 @@ pub struct Task {
- [pinningについて]で学んだように、`Pin<Box>` 型は、値をheap上に配置し、その値への `&mut` 参照の作成を防ぐことで、メモリ内で値が移動できないようにします。これは、async/awaitによって生成されたfutureが自己参照構造体である可能性があるため、重要です。つまり、futureが移動されたときに無効になるような自分自身へのポインタを含む可能性があります。
[_trait object_]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html
[_dynamically dispatched_]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#trait-objects-perform-dynamic-dispatch
[_dynamically dispatched_]: https://doc.rust-lang.org/book/ch18-02-trait-objects.html#trait-objects-perform-dynamic-dispatch
[pinningについて]: #pinliu-me
future から新しい `Task` 構造体を作成できるように、`new` 関数を作成します:

View File

@@ -125,7 +125,7 @@ pub trait Future {
The [associated type] `Output` specifies the type of the asynchronous value. For example, the `async_read_file` function in the diagram above would return a `Future` instance with `Output` set to `File`.
[associated type]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types
[associated type]: https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#associated-types
The [`poll`] method allows to check if the value is already available. It returns a [`Poll`] enum, which looks like this:
@@ -811,7 +811,7 @@ The `Task` struct is a newtype wrapper around a pinned, heap-allocated, and dyna
- As we learned in the [section about pinning], the `Pin<Box>` type ensures that a value cannot be moved in memory by placing it on the heap and preventing the creation of `&mut` references to it. This is important because futures generated by async/await might be self-referential, i.e., contain pointers to themselves that would be invalidated when the future is moved.
[_trait object_]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html
[_dynamically dispatched_]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#trait-objects-perform-dynamic-dispatch
[_dynamically dispatched_]: https://doc.rust-lang.org/book/ch18-02-trait-objects.html#trait-objects-perform-dynamic-dispatch
[section about pinning]: #pinning
To allow the creation of new `Task` structs from futures, we create a `new` function:
@@ -1578,7 +1578,7 @@ Let's look into some of the implementation details of this `run_ready_tasks` met
- To avoid the performance overhead of creating a waker on each poll, we use the `waker_cache` map to store the waker for each task after it has been created. For this, we use the [`BTreeMap::entry`] method in combination with [`Entry::or_insert_with`] to create a new waker if it doesn't exist yet and then get a mutable reference to it. For creating a new waker, we clone the `task_queue` and pass it together with the task ID to the `TaskWaker::new` function (implementation shown below). Since the `task_queue` is wrapped into an `Arc`, the `clone` only increases the reference count of the value, but still points to the same heap-allocated queue. Note that reusing wakers like this is not possible for all waker implementations, but our `TaskWaker` type will allow it.
[_destructuring_]: https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#destructuring-to-break-apart-values
[_destructuring_]: https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#destructuring-to-break-apart-values
[RFC 2229]: https://github.com/rust-lang/rfcs/pull/2229
[RFC 2229 impl]: https://github.com/rust-lang/rust/issues/53488

View File

@@ -129,7 +129,7 @@ pub trait Future {
O [tipo associado] `Output` especifica o tipo do valor assíncrono. Por exemplo, a função `async_read_file` no diagrama acima retornaria uma instância `Future` com `Output` definido como `File`.
[tipo associado]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types
[tipo associado]: https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#associated-types
O método [`poll`] permite verificar se o valor já está disponível. Ele retorna um enum [`Poll`], que se parece com isto:
@@ -816,7 +816,7 @@ A struct `Task` é um tipo newtype wrapper em torno de uma future fixada, alocad
- Como aprendemos na [seção sobre pinning], o tipo `Pin<Box>` garante que um valor não pode ser movido na memória colocando-o no heap e impedindo a criação de referências `&mut` a ele. Isso é importante porque futures gerados por async/await podem ser auto-referenciais, ou seja, conter ponteiros para si mesmos que seriam invalidados quando a future é movida.
[_trait object_]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html
[_dinamicamente despachados_]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#trait-objects-perform-dynamic-dispatch
[_dinamicamente despachados_]: https://doc.rust-lang.org/book/ch18-02-trait-objects.html#trait-objects-perform-dynamic-dispatch
[seção sobre pinning]: #pinning
Para permitir a criação de novas structs `Task` a partir de futures, criamos uma função `new`:
@@ -1586,7 +1586,7 @@ Nota do tradutor ([Richard Alves](https://github.com/richarddalves)): Na data de
- Para evitar a sobrecarga de desempenho de criar um waker em cada poll, usamos o mapa `waker_cache` para armazenar o waker para cada tarefa após ter sido criado. Para isso, usamos o método [`BTreeMap::entry`] em combinação com [`Entry::or_insert_with`] para criar um novo waker se ele ainda não existir e então obter uma referência mutável a ele. Para criar um novo waker, clonamos a `task_queue` e a passamos junto com o ID da tarefa para a função `TaskWaker::new` (implementação mostrada abaixo). Como a `task_queue` está encapsulada em um `Arc`, o `clone` apenas incrementa a contagem de referência do valor, mas ainda aponta para a mesma fila alocada em heap. Note que reutilizar wakers assim não é possível para todas as implementações de waker, mas nosso tipo `TaskWaker` permitirá isso.
[_desestruturação_]: https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#destructuring-to-break-apart-values
[_desestruturação_]: https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#destructuring-to-break-apart-values
[RFC 2229]: https://github.com/rust-lang/rfcs/pull/2229
[RFC 2229 impl]: https://github.com/rust-lang/rust/issues/53488
@@ -1824,4 +1824,4 @@ Para utilizar as notificações de waker da tarefa de teclado, criamos um novo t
Usando async/await, agora temos suporte básico para multitarefa cooperativa em nosso kernel. Embora multitarefa cooperativa seja muito eficiente, ela leva a problemas de latência quando tarefas individuais continuam executando por muito tempo, impedindo assim outras tarefas de executar. Por esta razão, faz sentido também adicionar suporte para multitarefa preemptiva ao nosso kernel.
No próximo post, introduziremos _threads_ como a forma mais comum de multitarefa preemptiva. Além de resolver o problema de tarefas de longa execução, threads também nos prepararão para utilizar múltiplos núcleos de CPU e executar programas de usuário não confiáveis no futuro.
No próximo post, introduziremos _threads_ como a forma mais comum de multitarefa preemptiva. Além de resolver o problema de tarefas de longa execução, threads também nos prepararão para utilizar múltiplos núcleos de CPU e executar programas de usuário não confiáveis no futuro.

View File

@@ -131,7 +131,7 @@ pub trait Future {
[Ассоциированный тип][associated type] `Output` определяет тип асинхронного значения. Например, функция `async_read_file` на приведенной выше диаграмме вернет экземпляр `Future` с `Output`, установленным как `File`.
[associated type]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types
[associated type]: https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#associated-types
Метод [`poll`] позволяет проверить, доступно ли значение. Он возвращает перечисление [`Poll`], которое выглядит следующим образом:
@@ -829,7 +829,7 @@ pub struct Task {
- Как мы узнали в [разделе о закреплении], тип `Pin<Box>` обеспечивает, что значение не может быть перемещено в памяти, помещая его в кучу и предотвращая создание `&mut` ссылок на него. Это важно, потому что футуры, генерируемые async/await, могут быть самоссылающимися, т.е. содержать указатели на себя, которые станут недействительными, если футура будет перемещена.
[_trait object_]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html
[_dynamically dispatched_]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#trait-objects-perform-dynamic-dispatch
[_dynamically dispatched_]: https://doc.rust-lang.org/book/ch18-02-trait-objects.html#trait-objects-perform-dynamic-dispatch
[разделе о закреплении]: #pinning
Чтобы разрешить создание новых структур `Task` из футур, мы создаём функцию `new`:
@@ -1599,7 +1599,7 @@ impl Executor {
- Чтобы избежать накладных расходов на создание waker при каждом опросе, мы используем дерево `waker_cache` для хранения waker для каждой задачи после ее создания. Для этого мы используем метод [`BTreeMap::entry`] в сочетании с [`Entry::or_insert_with`] для создания нового waker, если он ещё не существует, а затем получаем на него мутабельную ссылку. Для создания нового waker мы клонируем `task_queue` и передаём его вместе с идентификатором задачи в функцию `TaskWaker::new` (реализация ниже). Поскольку `task_queue` обёрнута в `Arc`, `clone` только увеличивает счётчик ссылок на значение, но всё равно указывает на ту же выделенную в куче очередь. Обратите внимание, что повторное использование wakers таким образом, невозможно для всех реализаций waker, но наш тип `TaskWaker` это позволит.
[_destructuring_]: https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#destructuring-to-break-apart-values
[_destructuring_]: https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#destructuring-to-break-apart-values
[RFC 2229]: https://github.com/rust-lang/rfcs/pull/2229
[RFC 2229 impl]: https://github.com/rust-lang/rust/issues/53488

View File

@@ -138,7 +138,7 @@ pub trait Future {
[关联类型][associated type] `Output` 用于指定异步值的类型。例如, 上图中的 `async_read_file` 函数将返回一个 `Future` 实例,其 `Output` 被设置为 `File`
[associated type]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types
[associated type]: https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#associated-types
[`poll`] 方法可用于检查值是否已就绪。它返回一个 [`Poll`] 枚举,其定义如下:
@@ -826,7 +826,7 @@ pub struct Task {
* 正如我们在 [固定 相关章节][section about pinning] 中学到的, `Pin<Box>` 类型通过将值放在堆上并组织创建 `&mut` 引用来确保它不会在内存中被移动。这一点很重要,因为由 async/await 生成的 future 可能是自引用的。也就是说会包含指向自己的指针,这些指针会在 future 移动过程中失效。
[_trait object_]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html
[_dynamically dispatched_]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#trait-objects-perform-dynamic-dispatch
[_dynamically dispatched_]: https://doc.rust-lang.org/book/ch18-02-trait-objects.html#trait-objects-perform-dynamic-dispatch
[section about pinning]: #pinning
为了从 future 创建新的 `Task` 结构体,我们创建了一个 `new` 函数:
@@ -1593,7 +1593,7 @@ impl Executor {
* 对于每个弹出的任务 ID我们从 `tasks` map 中获取对应任务的可变引用。由于我们的 `ScancodeStream` 实现在检查任务是否需要进入休眠状态前会先注册唤醒器,可能会出现一个已不存在的任务被唤醒的情况。这种情况下,我们只需忽略这次唤醒并继续处理队列里的下一个 ID。
* 为了避免每次轮询时创建唤醒器带来的性能开销,我们使用了 `waker_cache` map 用于存储每个任务创建后对应的唤醒器。为此,我们使用 [`BTreeMap::entry`] 方法结合 [`Entry::or_insert_with`] ,来在唤醒器不存在时创建新实例,然后获取其可变引用。为了创建新的唤醒器,我们克隆 `task_queue` 并将其与任务 ID 一同传递给 `TaskWaker::new` 函数(具体实现如下所示)。由于 `task_queue` 被封装在 `Arc` 中,克隆操作仅会增加该值的引用计数,但仍指向同一个堆分配的队列。请注意,并非所有唤醒器的实现都能像这样重复使用,不过我们的 `TaskWaker` 类型可以做到。
[_destructuring_]: https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#destructuring-to-break-apart-values
[_destructuring_]: https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#destructuring-to-break-apart-values
[RFC 2229]: https://github.com/rust-lang/rfcs/pull/2229
[RFC 2229 impl]: https://github.com/rust-lang/rust/issues/53488

View File

@@ -160,7 +160,7 @@ pub trait Future {
那個 關聯類型 [`associated type`] `Output` 指定了異步值的類型。
例如,上面的示例中的 `async_read_file` 函數將返回一個 `Output` 設置為 `File``Future` 實例。
[associated type]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types
[associated type]: https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#associated-types
那個 [`poll`] 方法允許檢查值是否已經可用。它返回一個 [`Poll`] 枚舉,看起來像這樣:
@@ -966,7 +966,7 @@ pub struct Task {
- 正如我們在 釘住操作 部分 [section about pinning] 學到的,`Pin<Box>` 類型通過將值放在堆上並防止創建對它的 `&mut` 引用來確保值在內存中不會被移動。這一點很重要,因為由 async/await 生成的 future 可能是自引用的,即包含指向自己的指針,當 future 被移動時這些指針將失效。
[_trait object_]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html
[_dynamically dispatched_]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#trait-objects-perform-dynamic-dispatch
[_dynamically dispatched_]: https://doc.rust-lang.org/book/ch18-02-trait-objects.html#trait-objects-perform-dynamic-dispatch
[section about pinning]: #pinning
爲允許從 future 創建新的 `Task` 結構體,我們創建一個 `new` 函數:
@@ -1836,7 +1836,7 @@ impl Executor {
- 爲避免在每次輪詢時創建喚醒器的性能開銷,我們使用 `waker_cache` map 來存儲每個任務的喚醒器。爲此,我們使用了 [`BTreeMap::entry`] 方法和 [`Entry::or_insert_with`] 來在它不存在時創建一個新的喚醒器,然後獲取一個對它的可變引用。爲創建一個新的喚醒器,我們克隆了 `task_queue`,並將它與任務 ID 一起傳遞給 `TaskWaker::new` 函數(下面展示了實現)。由於 `task_queue` 被包裝在一個 `Arc` 中,`clone` 只增加了值的引用計數,但仍然指向同一個堆分配的隊列。請注意,像這樣重用喚醒器對於所有的喚醒器實現來說都是不可能的,但我們的 `TaskWaker` 類型將允許它。
[_destructuring_]: https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#destructuring-to-break-apart-values
[_destructuring_]: https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#destructuring-to-break-apart-values
[RFC 2229]: https://github.com/rust-lang/rfcs/pull/2229
[RFC 2229 impl]: https://github.com/rust-lang/rust/issues/53488