Skip to content

Commit bfefda9

Browse files
authored
Apply suggestions from code review
1 parent 66b6edb commit bfefda9

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

docs/cpp_tricks.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# 应知应会 C++ 小技巧
22

3-
[toc]
3+
[TOC]
44

55
## 交换两个变量
66

@@ -1029,10 +1029,10 @@ cout << '\n';
10291029

10301030
> {{ icon.fun }} 而是分子了 :)
10311031
1032-
`std::cout``operator<<` 调用是线程安全的,不会被打断,但多个 `operator<<` 的调用在多线程环境中可能会 **交错** ,导致输出结果混乱
1033-
10341032
他们中间可能穿插了其他线程的 cout,从而导致你 `"the answer is"` 打印完后,被其他线程的 `'\n'` 插入进来,导致换行混乱。
10351033

1034+
> {{ icon.warn }} `std::cout``operator<<` 调用是线程安全的,不会被打断,但多个 `operator<<` 的调用在多线程环境中可能会 **交错** ,导致输出结果混乱。
1035+
10361036
> {{ icon.tip }} 更多细节请看我们的 [多线程专题](threading.md)
10371037
10381038
解决方法是,先创建一个只属于当前线程的 `ostringstream`,最后一次性调用一次 cout 的 `operator<<`,让“原子”的单位变成“一行”而不是一个字符串。
@@ -1051,15 +1051,15 @@ cout << std::format("the answer is {}\n", 42);
10511051

10521052
总之,就是要让 `operator<<` 只有一次,自然就是没有交错。
10531053

1054-
如果可以使用 C++20,就可改用 `std::osyncstream{ std::cout }` :
1054+
C++20 中,可以改用 `std::osyncstream(std::cout)` 代替 `std::cout` :
10551055

10561056
```cpp
1057-
std::osyncstream{ std::cout } << "the answer is " << 42 << '\n';
1057+
std::osyncstream(std::cout) << "the answer is " << 42 << '\n';
10581058
```
10591059
1060-
`std::osyncstream` 提供保证:所有对最终目标缓冲区(上例中是 [std::cout](https://zh.cppreference.com/w/cpp/io/cout "cpp/io/cout"))作出的输出将免除数据竞争,而且将不以任何方式穿插或截断
1060+
`std::osyncstream` 可以保证:1. 不会产生数据竞争;2. 不会发生穿插和截断。可以理解为 `std::osyncstream` 在构造时对缓冲区上锁,在析构时解锁
10611061
1062-
如果可以使用 C++23,就可改用 `std::println`
1062+
如果你的标准库支持 C++23,还可以用 `std::println`,这一整个打印操作也是原子的(第三方库如 `fmt::println` 亦可)
10631063
10641064
```cpp
10651065
std::println("the answer is {}", 42);

0 commit comments

Comments
 (0)