atomic_flag in C++
In this tutorial, you will learn about atomic_flag in C++. It is of atomic boolean type. Unlike other atomic operations, it is lock-free. And it does not provide load and store operations.
Member functions of atomic_flag
- Constructor
- The assignment operator (=)
- clear (atomically sets the value to false)
- test_and_set (atomically sets the value to true and obtain the previous value)
- test
- wait
- notify_one
- notify_all
Example of atomic_flag in C++
There are a few header files you need to import before implementing the program-
#include <thread> #include <vector> #include <iostream> #include <atomic>
The program below is an example of std::atomic_flag test_and_set_explicit.
std::atomic_flag lock = ATOMIC_FLAG_INIT; void f(int n) { for (int cnt = 0; cnt < 100; ++cnt) { while (lock.test_and_set(std::memory_order_acquire)) std::cout << "Output from thread " << n << '\n'; lock.clear(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:-
Output from thread 5 Output from thread 9 Output from thread 9 Output from thread 9 Output from thread 8 . .<1000 lines>
The output given above may vary each time you compile it and run.
We hope you have got a clear concept of this topic. If you need any help don’t hesitate to comment below.
Also read: How to flatten a 2-Dimensional vector in C++
Leave a Reply