Skip to content

Commit 55ff64e

Browse files
committed
book: Fix UB of ch8 usertests
-------- Reference: rcore-os/rCore-Tutorial-v3#140
1 parent e140b04 commit 55ff64e

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

source/chapter8/2lock.rst

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,7 @@ Rust 在标准库中提供了互斥锁 ``std::sync::Mutex<T>`` ,它可以包
418418
extern crate alloc;
419419
420420
use alloc::vec::Vec;
421+
use core::ptr::addr_of_mut;
421422
use user_lib::{exit, get_time, thread_create, waittid};
422423
423424
static mut A: usize = 0;
@@ -426,7 +427,7 @@ Rust 在标准库中提供了互斥锁 ``std::sync::Mutex<T>`` ,它可以包
426427
static mut PER_THREAD: usize = 0;
427428
428429
unsafe fn critical_section(t: &mut usize) {
429-
let a = &mut A as *mut usize;
430+
let a = addr_of_mut!(A);
430431
let cur = a.read_volatile();
431432
for _ in 0..500 {
432433
*t = (*t) * (*t) % 10007;
@@ -495,15 +496,15 @@ Rust 在标准库中提供了互斥锁 ``std::sync::Mutex<T>`` ,它可以包
495496
static mut OCCUPIED: bool = false;
496497
497498
unsafe fn lock() {
498-
while vload!(&OCCUPIED) {}
499+
while vload!(OCCUPIED) {}
499500
OCCUPIED = true;
500501
}
501502
502503
unsafe fn unlock() {
503504
OCCUPIED = false;
504505
}
505506
506-
我们使用一个新的全局变量 ``OCCUPIED`` 作为标记,表示当前是否有线程在临界区内。在 ``lock`` 的时候,我们等待 ``OCCUPIED`` 变为 false (注意这里的 ``vload!`` 来自用户库 ``user_lib`` ,和临界区中的 ``volatile_read`` 含义相同),这意味着没有线程在临界区内了,于是将标记修改为 true 并自己进入临界区。在退出临界区 ``unlock`` 的时候则只需将标记改成 false 。
507+
我们使用一个新的全局变量 ``OCCUPIED`` 作为标记,表示当前是否有线程在临界区内。在 ``lock`` 的时候,我们等待 ``OCCUPIED`` 变为 false (注意这里的 ``vload!`` 来自用户库 ``user_lib`` ,基于临界区中用到的 ``read_volatile`` 实现,含义相同),这意味着没有线程在临界区内了,于是将标记修改为 true 并自己进入临界区。在退出临界区 ``unlock`` 的时候则只需将标记改成 false 。
507508

508509
.. _term-busy-waiting:
509510
.. _term-spinning:
@@ -549,7 +550,7 @@ Rust 在标准库中提供了互斥锁 ``std::sync::Mutex<T>`` ,它可以包
549550
// Otherwise the compiler will assume that they will never
550551
// be changed on this thread. Thus, they will be accessed
551552
// only once!
552-
while vload!(&FLAG[j]) && vload!(&TURN) == j {}
553+
while vload!(FLAG[j]) && vload!(TURN) == j {}
553554
// while FLAG[j] && TURN == j {}
554555
}
555556

0 commit comments

Comments
 (0)