std::call_once
来自cppreference.com
![]() |
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <mutex> 中定义
|
||
template< class Function, class... Args > void call_once( std::once_flag& flag, Function&& f, Args&& args... ); |
(C++11 起) | |
。执行功能
f
一次,即使从多个线程调用. 原文:
Executes the function
f
exactly once, even if called from several threads. 。每个组的
call_once
调用接收相同的std::once_flag对象的将符合下列要求:。原文:
Each group of
call_once
invocations that receives the same std::once_flag object will meet the following requirements:- 。
f
该组中的调用)。将被选择用于执行的函数,它是未定义。所选择的功能call_once
调用传递给运行在同一个线程中.原文:
Exactly one execution of exactly one of the functions (passed as
f
to the invocations in the group) is performed. It is undefined which function will be selected for execution. The selected function runs in the same thread as the call_once
invocation it was passed to.- 。没有调用成功完成之前,上述执行所选择的功能组中的回报,也就是说,不通过异常退出.原文:No invocation in the group returns before the abovementioned execution of the selected function is completed successfully, that is, doesn't exit via an exception.
- 。如果所选的功能异常退出,它会传播给调用者。然后,选择和执行的另一项功能.原文:If the selected function exits via exception, it is propagated to the caller. Another function is then selected and executed.
目录 |
[编辑] 。参数。
flag | - | 。一个对象,其中一个功能被执行。
原文: an object, for which exactly one function gets executed |
f | - | 。要调用的函数。
|
args... | - | 。传递给函数的参数。
|
===。 返回值。===
。 (无)。
[编辑] 。例外。
- 。 std::system_error任何条件阻止
call_once
执行所指定的调用。原文:std::system_error if any condition prevents calls tocall_once
from executing as specified - 。
f
抛出的任何异常。
[编辑] 。为例。
#include <iostream> #include <thread> #include <mutex> std::once_flag flag; void do_once() { std::call_once(flag, [](){ std::cout << "Called once" << std::endl; }); } int main() { std::thread t1(do_once); std::thread t2(do_once); std::thread t3(do_once); std::thread t4(do_once); t1.join(); t2.join(); t3.join(); t4.join(); }
输出:
Called once
[编辑] 。另请参阅。
(C++11) |
call_once的辅助对象,以确保调用该函数一次 原文: helper object to ensure that call_once invokes the function only once (类) |