15

According to the C++17 standard, [support.signal], the atomic object should satisfy the following requirements to be used in a signal handler:

  • [...], or
  • f is a non-static member function invoked on an object A, such that A.is_­lock_­free() yields true, or
  • f is a non-member function, and for every pointer-to-atomic argument A passed to f, atomic_­is_­lock_­free(A) yields true.

std::atomic_flag doesn't fit here formally (there is no is_lock_free method and atomic_is_lock_free can't be called with std::atomic_flag object). Though intuitively, it's very close (it's atomic and lock-free). Does it mean that std::atomic_flag can't be used in a signal handler, or it's just a C++ standard that needs clarification?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • 2
    `std::atomic_flag` is always lock free, so it seems to me like it should be usable in a signal handler, but I agree that it doesn't seem legal by the current wording. I don't see any existing standard defects relating to it. Assuming no one more knowledgable than myself has a better answer, there are instructions for submitting a standard defect report [here](https://isocpp.org/std/submit-issue). – Miles Budnek Aug 18 '22 at 08:37
  • why do you need specifically atomic_flag? can you use atomic? their performance is exactly the same – Andriy Tylychko Aug 22 '22 at 20:24
  • @AndriyTylychko what to use in the signal handler is really out of the scope of my question, but yes, I just use atomic bool – breathfidgeting Aug 23 '22 at 04:54
  • Also, note that atomic_flag is guaranteed to be lock-free, unlike atomic bool, where you have to check lock-free in runtime with method is_lock_free. I guess in practice it's always true though – breathfidgeting Aug 23 '22 at 04:55

1 Answers1

3

What you have pointed out is a defect in the standard that has been resolved in LWG 3756 Is the std::atomic_flag class signal-safe?.

The new wording obviously allows for std::atomic_flag to be used in signal handlers:

A plain lock-free atomic operation is an invocation of a function f from [atomics], such that:

  • [...]
  • f is a non-static member function of class atomic_flag, or
  • f is a non-member function, and the first parameter of f has type cv atomic_flag*, or
  • [...]

An evaluation is signal-safe unless it includes one of the following:

  • a call to any standard library function, except for plain lock-free atomic operations and functions explicitly identified as signal-safe;
  • [...]

It's probably safe to assume that std::atomic_flag is signal-safe in any standard prior to C++23 too, given that it's intended to be, and basically satisfies the requirements, even if not technically.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96