Why is volatile not part of sig_atomic_t
Asked Answered
I

2

6

On my platform (X86, Fedora, gcc 9.1.1) sig_atomic_t is typedef'd to a plain int.

In the C++ standard, sig_atomic_t is always used with the volatile qualifier.
I understand why volatile is needed, but why is it not part of the type then ?

Something like:

using sig_atomic_t = volatile int;
Inconsonant answered 15/6, 2019 at 18:3 Comment(0)
S
3

This is inherited from C. The C definition, while allowing for sig_atomic_t to be volatile qualified, does not require it. All the example uses in the standard doc I've looked (N1570) at are given as volatile sig_atomic_t.

These days it may be better to use std:atomic and the other capabilities specified in the <atomic> header when feasible. (Also see sig_atomic_t on cppreference.)

Snarl answered 15/6, 2019 at 18:22 Comment(2)
In portable code, std::atomic is not recommended for signal handlers because there is a potential risk of deadlock. Also, but less important, the default seq/cst makes it stronger than necessaryShawnna
@Shawnna I've toned down that recommendation a bit.Snarl
H
3

C89 says that it's

the integral type of an object that can be accessed as an atomic entity, even in the presence of asynchronous interrupts.

volatile not specified, probably because qualifiers were a new thing when the first standard was made.

C99 adds "possibly volatile-qualified.

I suppose it's backwards compatibility from then on combined with "nobody cares enough", since signal-handling is a relatively minor part of most project.

Also somebody could presumably use it in a context where volatile is not required (e.g., to store a copy of a flag used for communication with signal handlers) and in non-GNU C (again, backwards compatibility) it's basically impossible to map a type to a less qualified version of that type, which makes an implementation that chooses to omit the qualifier more flexible.

Hunks answered 15/6, 2019 at 18:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.