Skip to content

Commit 813212b

Browse files
committed
修改 spinlock_mutex 的实现,添加 noexcept
1 parent b70f15e commit 813212b

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

md/05内存模型与原子操作.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -267,11 +267,12 @@ bool r = f.test_and_set();
267267
class spinlock_mutex {
268268
std::atomic_flag flag{};
269269
public:
270-
void lock() {
270+
spinlock_mutex()noexcept = default;
271+
void lock()noexcept {
271272
while (flag.test_and_set(std::memory_order_acquire));
272273
}
273274

274-
void unlock() {
275+
void unlock()noexcept {
275276
flag.clear(std::memory_order_release);
276277
}
277278
};
@@ -288,7 +289,7 @@ void f(){
288289
}
289290
```
290291

291-
> [运行](https://godbolt.org/z/9rs9sxsns)测试。
292+
> [运行](https://godbolt.org/z/T583YYTh8)测试。
292293
293294
稍微聊一下原理,我们的 `spinlock_mutex` 对象中存储的 `flag` 对象在默认构造时是清除 (`false`) 状态。在 `lock()` 函数中调用 `test_and_set` 函数,它是原子的,只有一个线程能成功调用并将 `flag` 的状态原子地更改为设置 (`true`),并返回它先前的值 (`false`)。此时,该线程成功获取了锁,退出循环。
294295

0 commit comments

Comments
 (0)