3

I know that different architectures may provide different ways to let developer detect whether the cpu is running in ISR now, e.g. reading a register.

But I do found that in some BSP code, they use a global variable,it is called g_in_isr, as a flag to indicating whether cpu running in ISR. When an interrupt occurred the interrupt handler will perform g_in_isr++ operation on entery and g_in_isr-- on exit.

I am wondering if this way is safe on the architectures which allows nested interrupt. In most architectures, g_in_isr++ or g_in_isr-- is not atomic operation (am I right?), what if an high priority interrupt comes while an existing interrupt handler is doing g_in_isr++ operation? Doesn't it cause problems?

Update (2016-03-27)

Yeah, I know it is architecture dependent, but I want to know the general case. Let us assume that g_in_isr++ is not atomic, it is indeed not atomic on most architecture, am I right? Of course we also don't use any compiler magic to make it atomic.

Now at such a case, would it cause problems?

cifer
  • 615
  • 1
  • 9
  • 25
  • 1
    It might, it could, it's up to the OS designer to ensure it does not. This is an OS design issue, not C -specific. – Martin James Mar 26 '16 at 10:49
  • What CPU and what CPU instructions are generated by the compiler for those C statements? Do interrupts need to be enabled within the ISR to allow for nested interrupts? – kkrambo Mar 26 '16 at 13:24
  • @kkrambo Sorry, I have updated my question so it may looks cleared now. May you answer it now? Thanks! – cifer Mar 27 '16 at 03:05

1 Answers1

0

The C language did not specify useful atomic semantics prior to C11, but one thing exists. The type sig_atomic_t is an integer with guaranteed atomic access, cf. ISO 9899:1999 §7.14 ¶2:

2 The type defined is

sig_atomic_t

which is the (possibly volatile-qualified) integer type of an object that can be accessed as an atomic entity, even in the presence of asynchronous interrupts.

If you use a global variable of type sig_atomic_t to indicate that a signal was delivered, that is safe. However, there are no operations like atomic increment defined in C99.

In the C11 language, you could use an _Atomic int for this purpose. Operations on this type work as expected.

fuz
  • 88,405
  • 25
  • 200
  • 352
  • Sorry but I was not willing to know how to tell the compiler to generate an atomic operation for me. I have updated my question so it may looks cleared now. May you re-read it now? Thanks! – cifer Mar 27 '16 at 03:04