CodeBlanks Logo Icon CodeBlanks

atomic flag

Learn spinlock with atomic_flag.

atomic_flag

std::atomic_flag is the simplest atomic type. It has only two states: set and clear. It is guaranteed to be lock-free on all hardware (is_lock_free is always true). It is initialized to clear with ATOMIC_FLAG_INIT.

f.test_and_set() returns the previous state and sets the flag. f.clear() clears the flag. These two operations make atomic_flag ideal for a spinlock that loops while busy. Unlike other atomic types, atomic_flag has no load or store members.

Spinlock pattern

A spinlock is a lock that loops while waiting for the lock. The pattern while (f.test_and_set()) { /* wait */ } spins until it acquires the flag. When done, f.clear(); releases it. Unlike a mutex, the thread does not sleep; it spins.

Spinlocks are effective for short critical sections because there is no sleep/wake cost. For long critical sections they waste CPU; a mutex is preferred there. A spinlock built with std::atomic_flag is the most basic pattern of lock-free synchronization in the standard library.

Practice atomic_flag test

Initialize std::atomic_flag f = ATOMIC_FLAG_INIT;. Get the first state and set it with bool was_set = f.test_and_set();. Write std::cout << was_set << " " << f.test_and_set();: the previous state and the second call's result (now 1 since the flag is set).

Starter code

main.cpp
#include <iostream>
#include <atomic>

int main() {
    // Initialize atomic_flag, print via test_and_set
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <atomic>

int main() {
    std::atomic_flag f = ATOMIC_FLAG_INIT;
    bool was_set = f.test_and_set();
    std::cout << was_set << " " << f.test_and_set();
    return 0;
}

Expected output

0 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each expression to its role

Term Meaning
std::atomic_flag Simplest atomic type
f.test_and_set() Return old state, set it
f.clear() Clear the flag
ATOMIC_FLAG_INIT Clear initialization

2 Complete the test_and_set line

Question
std::atomic_flag f = ATOMIC_FLAG_INIT;
bool was_set = f.____();
Answer
std::atomic_flag f = ATOMIC_FLAG_INIT;
bool was_set = f.test_and_set();

Explanation: f.test_and_set() returns the old state and sets the flag.

3 Which lock is built with atomic_flag?

  • Mutex
  • Recursive lock
  • Semaphore
  • Spinlock Correct answer

Explanation: atomic_flag is ideal for building a spinlock.

All lessons in Advanced