Skip to content

Commit

Permalink
Update ch19-01-unsafe-rust.md (#144)
Browse files Browse the repository at this point in the history
  • Loading branch information
mirthfulLee committed Sep 27, 2023
1 parent f49d3d1 commit e8a7ec0
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion src/ch19-01-unsafe-rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ fn main() {

<span class="caption">示例 19-10: 读取或修改一个可变静态变量是不安全的</span>

就像常规变量一样,我们使用 `mut` 关键来指定可变性。任何读写 `COUNTER` 的代码都必须位于 `unsafe` 块中。这段代码可以编译并如期打印出 `COUNTER: 3`,因为这是单线程的。拥有多个线程访问 `COUNTER` 则可能导致数据竞争。
就像常规变量一样,我们使用 `mut` 关键字来指定可变性。任何访问或修改 `COUNTER` 的代码都必须位于 `unsafe` 块中。这段代码可以编译并如期打印出 `COUNTER: 3`,因为这是单线程的。拥有多个线程访问 `COUNTER` 则可能导致数据竞争。

拥有可以全局访问的可变数据,难以保证不存在数据竞争,这就是为何 Rust 认为可变静态变量是不安全的。任何可能的情况,请优先使用第 16 章讨论的并发技术和线程安全智能指针,这样编译器就能检测不同线程间的数据访问是否是安全的。

Expand Down

0 comments on commit e8a7ec0

Please sign in to comment.