File tree Expand file tree Collapse file tree 1 file changed +4
-3
lines changed Expand file tree Collapse file tree 1 file changed +4
-3
lines changed Original file line number Diff line number Diff line change @@ -267,11 +267,12 @@ bool r = f.test_and_set();
267
267
class spinlock_mutex {
268
268
std::atomic_flag flag{};
269
269
public:
270
- void lock() {
270
+ spinlock_mutex()noexcept = default;
271
+ void lock()noexcept {
271
272
while (flag.test_and_set(std::memory_order_acquire));
272
273
}
273
274
274
- void unlock() {
275
+ void unlock()noexcept {
275
276
flag.clear(std::memory_order_release);
276
277
}
277
278
};
@@ -288,7 +289,7 @@ void f(){
288
289
}
289
290
```
290
291
291
- > [ 运行] ( https://godbolt.org/z/9rs9sxsns ) 测试。
292
+ > [ 运行] ( https://godbolt.org/z/T583YYTh8 ) 测试。
292
293
293
294
稍微聊一下原理,我们的 ` spinlock_mutex ` 对象中存储的 ` flag ` 对象在默认构造时是清除 (` false ` ) 状态。在 ` lock() ` 函数中调用 ` test_and_set ` 函数,它是原子的,只有一个线程能成功调用并将 ` flag ` 的状态原子地更改为设置 (` true ` ),并返回它先前的值 (` false ` )。此时,该线程成功获取了锁,退出循环。
294
295
You can’t perform that action at this time.
0 commit comments