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

  1. Constructor
  2. The assignment operator (=)
  3. clear (atomically sets the value to false)
  4. test_and_set (atomically sets the value to true and obtain the previous value)
  5. test
  6. wait
  7. notify_one
  8. 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++

ratio_equal() and ratio_not_equal() in C++

Leave a Reply

Your email address will not be published.