call_once, once_flag, ONCE_FLAG_INIT
提供: cppreference.com
(c/thread/ONCE FLAG INITから転送)
<tbody>
</tbody>
| ヘッダ <threads.h> で定義
|
||
void call_once( once_flag* flag, void (*func)(void) ); |
(1) | (C11以上) |
typedef /* unspecified */ once_flag |
(2) | (C11以上) |
#define ONCE_FLAG_INIT /* unspecified */ |
(3) | (C11以上) |
1) 複数のスレッドから呼ばれた場合でも、関数
func をちょうど一度だけ呼びます。 関数 func の完了は同じ flag 変数を使用するすべての以前および今後の call_once の呼び出しに対して同期します。2)
call_once によって使用されるフラグを保持できる完全オブジェクト型。3)
once_flag 型のオブジェクトを初期化するために使用できる値に展開されます。引数
| flag | - | func が一度だけ呼ばれることを保証するために使用される call_once 型のオブジェクトを指すポインタ
|
| func | - | 一度だけ実行する関数 |
戻り値
(なし)
ノート
この関数と同等な POSIX の関数は pthread_once です。
例
Run this code
#include <stdio.h>
#include <threads.h>
void do_once(void) {
puts("called once");
}
static once_flag flag = ONCE_FLAG_INIT;
int func(void* data)
{
call_once(&flag, do_once);
}
int main(void)
{
thrd_t t1, t2, t3, t4;
thrd_create(&t1, func, NULL);
thrd_create(&t2, func, NULL);
thrd_create(&t3, func, NULL);
thrd_create(&t4, func, NULL);
thrd_join(t1, NULL);
thrd_join(t2, NULL);
thrd_join(t3, NULL);
thrd_join(t4, NULL);
}
出力:
called once
参考文献
- C11 standard (ISO/IEC 9899:2011):
- 7.26.2.1 The call_once function (p: 378)
- 7.26.1/3 ONCE_FLAG_INIT (p: 376)
関連項目
call_once の C++リファレンス
|