Lokesh Waran
Lokesh Waran

Reputation: 69

Can a critical section be interrupted in OS? What are the effects if implemented in user section or kernel code?

Recently I was asked this question in an interview about the critical section effect when interrupted by an interrupt if we implemented it through mutex. Is there are any effect if critical section implemented in user code or in kernel code.

Upvotes: 0

Views: 769

Answers (1)

user9483537
user9483537

Reputation:

It depends on the scope of the critical section and the implementation of the critical section. A critical section is a constraint applied to a section of code that prevents concurrent access to some shared data.

On single-core microcontrollers

The following types of data need to be protected.

  1. Data only shared between multiple threads
  2. Data only shared between multiple interrupts
  3. Data shared between threads and interrupts

A critical section can be implemented by

  1. Disabling all interrupts (available in user context and in the OS kernel context)
  2. Using OS software mutex (available in user context)

For option 1, since the Operating System, specifically the context switcher is implemented using interrupts, this will also effectively disable OS context switching and temporarily multi-threading. This makes sure only the current thread or interrupt context can access the data. Thus disabling interrupts is an effective protection for all 3 types of shared data. However, temporarily disabling interrupts can increase the interrupt latency of the microcontroller and the scheduling latency of the OS, since neither the interrupt handler nor the OS can respond until interrupts are re-enabled.

If the data is only shared between threads, the critical section can optionally be implemented using an OS software mutex. The OS restricts access to a locked mutex by one thread at a time, and if threads only access the data when the lock on the mutex is acquired, the access to the data is protected. OS software mutexes protect shared data through OS scheduling, and the OS and interrupts remain fully operative during the critical section. This type of implementation does not prevent interrupts from being handled during the critical section, nor does it prevent the scheduling of unaffected threads.

OS software mutexes are not effective at protecting data shared between threads and interrupts, since the OS cannot prevent interrupts through scheduling.

In case where the operating system itself relies on shared data, or when there is no operating system, since OS mutexes are not yet available, it is common to see operating system code or baremetal code disabling interrupts to obtain a critical section.

Upvotes: 1

Related Questions