void notify_one() const noexcept; // (1) C++20
constexpr void notify_one() const noexcept; // (1) C++26
概要
待機しているスレッドをひとつ起床させる。
この関数は、wait()
関数によるブロッキング待機を解除する。
テンプレートパラメータ制約
- C++26 :
is_const_v<T>
がfalse
であること
効果
起床待機している少なくともひとつのアトミックオブジェクトの待機を解除する
戻り値
なし
例外
投げない
例
#include <iostream>
#include <atomic>
#include <thread>
class my_mutex {
bool state_ = false; // false:unlock, true:lock
public:
void lock() noexcept {
std::atomic_ref r{state_};
while (r.exchange(true) == true) {
r.wait(true);
}
}
void unlock() noexcept {
std::atomic_ref r{state_};
r.store(false);
r.notify_one();
}
};
my_mutex mut;
void print(int x) {
mut.lock();
std::cout << x << std::endl;
mut.unlock();
}
int main()
{
std::thread t1 {[] {
for (int i = 0; i < 5; ++i) {
print(i);
}
}};
std::thread t2 {[] {
for (int i = 5; i < 10; ++i) {
print(i);
}
}};
t1.join();
t2.join();
}
45
#include <iostream>
#include <atomic>
#include <thread>
class my_mutex {
bool state_ = false; // false:unlock, true:lock
public:
void lock() noexcept {
std::atomic_ref r{state_};
while (r.exchange(true) == true) {
r.wait(true);
}
}
void unlock() noexcept {
std::atomic_ref r{state_};
r.store(false);
r.notify_one();
出力例
0
5
1
6
2
7
3
8
4
9
バージョン
言語
- C++20
処理系
- Clang: 9.0 ❌
- GCC: 9.2 ❌
- Visual C++: 2019 Update 3 ❌
参照
- P0514R4 Efficient concurrent waiting for C++20
- ogiroux/atomic_wait - Sample implementation of C++20 atomic_wait/notify
- P1643R1 Add wait/notify to
atomic_ref
- P1960R0 NB Comment Changes Reviewed by SG1
- 宣言に
const
を追加
- 宣言に
- P3323R1 cv-qualified types in
atomic
andatomic_ref
- C++26でCV修飾されたテンプレート引数を受け取れるようになった
- P3309R3
constexpr atomic
andatomic_ref
- C++26で
constexpr
に対応した
- C++26で