Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is volatile not part of sig_atomic_t

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;
like image 608
Tootsie Avatar asked Jun 15 '19 18:06

Tootsie


People also ask

What is a Sig_atomic_t?

The type sig_atomic_t is the integer type of an object that can be accessed as an atomic entity even in the presence of asynchronous interrupts.

Is Sig_atomic_t thread safe?

Note that sig_atomic_t is not thread-safe, only async-signal safe. Atomics involve two types of barriers: Compiler barrier. It makes sure that the compiler does not reorder reads/writes from/to an atomic variable relative to reads and writes to other variables.


2 Answers

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.)

like image 97
1201ProgramAlarm Avatar answered Oct 17 '22 06:10

1201ProgramAlarm


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.

like image 24
PSkocik Avatar answered Oct 17 '22 06:10

PSkocik