- C 标准库
- C 标准库
- C++ 标准库
- C++ 库 - 主页
- C++ 库 - <fstream>
- C++ 库 - <iomanip>
- C++ 库 - <ios>
- C++ 库 - <iosfwd>
- C++ 库 - <iostream>
- C++ 库 - <istream>
- C++ 库 - <ostream>
- C++ 库 - <sstream>
- C++ 库 - <streambuf>
- C++ 库 - <原子>
- C++ 库 - <复杂>
- C++ 库 - <异常>
- C++ 库 - <功能>
- C++ 库 - <限制>
- C++ 库 - <语言环境>
- C++ 库 - <内存>
- C++ 库 - <新>
- C++ 库 - <数字>
- C++ 库 - <正则表达式>
- C++ 库 - <stdexcept>
- C++ 库 - <字符串>
- C++ 库 - <线程>
- C++ 库 - <元组>
- C++ 库 - <类型信息>
- C++ 库 - <实用程序>
- C++ 库 - <valarray>
C++ 原子库 - flag_test_and_set
描述
它以原子方式将标志设置为 true 并返回其先前的值。
宣言
以下是 std::atomic_flag_test_and_set 的声明。
bool atomic_flag_test_and_set( std::atomic_flag* p );
C++11
bool atomic_flag_test_and_set( volatile std::atomic_flag* p );
以下是 std::atomic_flag_test_and_set_explicit 的声明。
bool atomic_flag_test_and_set_explicit( volatile std::atomic_flag* p,
std::memory_order order );
C++11
bool atomic_flag_test_and_set_explicit( std::atomic_flag* p,
std::memory_order order );
参数
p - 它用于指向 std::atomic_flag 的指针进行访问。
order - 用于同步此操作的内存排序。
返回值
它返回 p 指向的标志先前保存的值。
例外情况
No-noexcept - 该成员函数从不抛出异常。
例子
在下面的 std::atomic_flag_test_and_set_explicit 示例中。
#include <thread>
#include <vector>
#include <iostream>
#include <atomic>
std::atomic_flag lock = ATOMIC_FLAG_INIT;
void f(int n) {
for (int cnt = 0; cnt < 100; ++cnt) {
while(std::atomic_flag_test_and_set_explicit(&lock, std::memory_order_acquire))
;
std::cout << "Output from thread " << n << '\n';
std::atomic_flag_clear_explicit(&lock, std::memory_order_release);
}
}
int main() {
std::vector<std::thread> v;
for (int n = 0; n < 10; ++n) {
v.emplace_back(f, n);
}
for (auto& t : v) {
t.join();
}
}
示例输出应该是这样的 -
Output from thread 0 Output from thread 1 Output from thread 0 Output from thread 0 Output from thread 1 Output from thread 1 Output from thread 0 Output from thread 0 Output from thread 1 Output from thread 0 ....................
原子.htm