Real-time operating system

A real-time operating system (RTOS) is an operating system (OS) for real-time computing applications that processes data and events that have critically defined time constraints. An RTOS is distinct from a time-sharing operating system, such as Unix, which manages the sharing of system resources with a scheduler, data buffers, or fixed task prioritization in multitasking or multiprogramming environments. All operations must verifiably complete within given time and resource constraints or else fail safe. Real-time operating systems are event-driven and preemptive, meaning the OS can monitor the relevant priority of competing tasks, and make changes to the task priority. Event-driven systems switch between tasks based on their priorities, while time-sharing systems switch the task based on clock interrupts.[1]

Characteristics

A key characteristic of an RTOS is the level of its consistency concerning the amount of time it takes to accept and complete an application's task; the variability is "jitter".[2] A "hard" real-time operating system (hard RTOS) has less jitter than a "soft" real-time operating system (soft RTOS); a late answer is a wrong answer in a hard RTOS while a late answer is acceptable in a soft RTOS. The chief design goal is not high throughput, but rather a guarantee of a soft or hard performance category. An RTOS that can usually or generally meet a deadline is a soft real-time OS, but if it can meet a deadline deterministically it is a hard real-time OS.[3]

An RTOS has an advanced algorithm for scheduling. Scheduler flexibility enables a wider, computer-system orchestration of process priorities, but a real-time OS is more frequently dedicated to a narrow set of applications. Key factors in a real-time OS are minimal interrupt latency and minimal thread switching latency; a real-time OS is valued more for how quickly or how predictably it can respond than for the amount of work it can perform in a given period of time.[4]

Design philosophies

An RTOS is an operating system in which the time taken to process an input stimulus is less than the time lapsed until the next input stimulus of the same type.

The most common designs are:

Time sharing designs switch tasks more often than strictly needed, but give smoother multitasking, giving the illusion that a process or user has sole use of a machine.

Early CPU designs needed many cycles to switch tasks during which the CPU could do nothing else useful. Because switching took so long, early OSes tried to minimize wasting CPU time by avoiding unnecessary task switching.

Scheduling

In typical designs, a task has three states:

  1. Running (executing on the CPU);
  2. Ready (ready to be executed);
  3. Blocked (waiting for an event, I/O for example).

Most tasks are blocked or ready most of the time because generally only one task can run at a time per CPU core. The number of items in the ready queue can vary greatly, depending on the number of tasks the system needs to perform and the type of scheduler that the system uses. On simpler non-preemptive but still multitasking systems, a task has to give up its time on the CPU to other tasks, which can cause the ready queue to have a greater number of overall tasks in the ready to be executed state (resource starvation).

Usually, the data structure of the ready list in the scheduler is designed to minimize the worst-case length of time spent in the scheduler's critical section, during which preemption is inhibited, and, in some cases, all interrupts are disabled, but the choice of data structure depends also on the maximum number of tasks that can be on the ready list.

If there are never more than a few tasks on the ready list, then a doubly linked list of ready tasks is likely optimal. If the ready list usually contains only a few tasks but occasionally contains more, then the list should be sorted by priority, so that finding the highest priority task to run does not require traversing the list. Instead, inserting a task requires walking the list.

During this search, preemption should not be inhibited. Long critical sections should be divided into smaller pieces. If an interrupt occurs that makes a high priority task ready during the insertion of a low priority task, that high priority task can be inserted and run immediately before the low priority task is inserted.

The critical response time, sometimes called the flyback time, is the time it takes to queue a new ready task and restore the state of the highest priority task to running. In a well-designed RTOS, readying a new task will take 3 to 20 instructions per ready-queue entry, and restoration of the highest-priority ready task will take 5 to 30 instructions.

In advanced systems, real-time tasks share computing resources with many non-real-time tasks, and the ready list can be arbitrarily long. In such systems, a scheduler ready list implemented as a linked list would be inadequate.

Algorithms

Some commonly used RTOS scheduling algorithms are:[5]

Intertask communication and resource sharing

A multitasking operating system like Unix is poor at real-time tasks. The scheduler gives the highest priority to jobs with the lowest demand on the computer, so there is no way to ensure that a time-critical job will have access to enough resources. Multitasking systems must manage sharing data and hardware resources among multiple tasks. It is usually unsafe for two tasks to access the same specific data or hardware resource simultaneously.[6] There are three common approaches to resolve this problem:

Temporarily masking/disabling interrupts

General-purpose operating systems usually do not allow user programs to mask (disable) interrupts, because the user program could control the CPU for as long as it is made to. Some modern CPUs do not allow user mode code to disable interrupts as such control is considered a key operating system resource. Many embedded systems and RTOSs, however, allow the application itself to run in kernel mode for greater system call efficiency and also to permit the application to have greater control of the operating environment without requiring OS intervention.

On single-processor systems, an application running in kernel mode and masking interrupts is the lowest overhead method to prevent simultaneous access to a shared resource. While interrupts are masked and the current task does not make a blocking OS call, the current task has exclusive use of the CPU since no other task or interrupt can take control, so the critical section is protected. When the task exits its critical section, it must unmask interrupts; pending interrupts, if any, will then execute. Temporarily masking interrupts should only be done when the longest path through the critical section is shorter than the desired maximum interrupt latency. Typically this method of protection is used only when the critical section is just a few instructions and contains no loops. This method is ideal for protecting hardware bit-mapped registers when the bits are controlled by different tasks.

Mutexes

When the shared resource must be reserved without blocking all other tasks (such as waiting for Flash memory to be written), it is better to use mechanisms also available on general-purpose operating systems, such as a mutex and OS-supervised interprocess messaging. Such mechanisms involve system calls, and usually invoke the OS's dispatcher code on exit, so they typically take hundreds of CPU instructions to execute, while masking interrupts may take as few as one instruction on some processors.

A (non-recursive) mutex is either locked or unlocked. When a task has locked the mutex, all other tasks must wait for the mutex to be unlocked by its owner - the original thread. A task may set a timeout on its wait for a mutex. There are several well-known problems with mutex based designs such as priority inversion and deadlocks.

In priority inversion a high priority task waits because a low priority task has a mutex, but the lower priority task is not given CPU time to finish its work. A typical solution is to have the task that owns a mutex 'inherit' the priority of the highest waiting task. But this simple approach gets more complex when there are multiple levels of waiting: task A waits for a mutex locked by task B, which waits for a mutex locked by task C. Handling multiple levels of inheritance causes other code to run in high priority context and thus can cause starvation of medium-priority threads.

In a deadlock, two or more tasks lock mutex without timeouts and then wait forever for the other task's mutex, creating a cyclic dependency. The simplest deadlock scenario occurs when two tasks alternately lock two mutex, but in the opposite order. Deadlock is prevented by careful design.

Message passing

The other approach to resource sharing is for tasks to send messages in an organized message passing scheme. In this paradigm, the resource is managed directly by only one task. When another task wants to interrogate or manipulate the resource, it sends a message to the managing task. Although their real-time behavior is less crisp than semaphore systems, simple message-based systems avoid most protocol deadlock hazards, and are generally better-behaved than semaphore systems. However, problems like those of semaphores are possible. Priority inversion can occur when a task is working on a low-priority message and ignores a higher-priority message (or a message originating indirectly from a high priority task) in its incoming message queue. Protocol deadlocks can occur when two or more tasks wait for each other to send response messages.

Interrupt handlers and the scheduler

Since an interrupt handler blocks the highest priority task from running, and since real-time operating systems are designed to keep thread latency to a minimum, interrupt handlers are typically kept as short as possible. The interrupt handler defers all interaction with the hardware if possible; typically all that is necessary is to acknowledge or disable the interrupt (so that it won't occur again when the interrupt handler returns) and notify a task that work needs to be done. This can be done by unblocking a driver task through releasing a semaphore, setting a flag or sending a message. A scheduler often provides the ability to unblock a task from interrupt handler context.

An OS maintains catalogues of objects it manages such as threads, mutexes, memory, and so on. Updates to this catalogue must be strictly controlled. For this reason, it can be problematic when an interrupt handler calls an OS function while the application is in the act of also doing so. The OS function called from an interrupt handler could find the object database to be in an inconsistent state because of the application's update. There are two major approaches to deal with this problem: the unified architecture and the segmented architecture. RTOSs implementing the unified architecture solve the problem by simply disabling interrupts while the internal catalogue is updated. The downside of this is that interrupt latency increases, potentially losing interrupts. The segmented architecture does not make direct OS calls but delegates the OS related work to a separate handler. This handler runs at a higher priority than any thread but lower than the interrupt handlers. The advantage of this architecture is that it adds very few cycles to interrupt latency. As a result, OSes which implement the segmented architecture are more predictable and can deal with higher interrupt rates compared to the unified architecture.[citation needed]

Similarly, the System Management Mode on x86 compatible hardware can take a lot of time before it returns control to the operating system.

Memory allocation

Memory allocation is more critical in a real-time operating system than in other operating systems.

First, for stability there cannot be memory leaks (memory that is allocated but not freed after use). The device should work indefinitely, without ever needing a reboot.[citation needed] For this reason, dynamic memory allocation is frowned upon.[citation needed] Whenever possible, all required memory allocation is specified statically at compile time.

Another reason to avoid dynamic memory allocation is memory fragmentation. With frequent allocation and releasing of small chunks of memory, a situation may occur where available memory is divided into several sections and the RTOS cannot allocate a large enough continuous block of memory, although there is enough free memory. Secondly, speed of allocation is important. A standard memory allocation scheme scans a linked list of indeterminate length to find a suitable free memory block,[7] which is unacceptable in a RTOS since memory allocation has to occur within a certain amount of time.

Because mechanical disks have much longer and more unpredictable response times, swapping to disk files is not used for the same reasons as RAM allocation discussed above.

The simple fixed-size-blocks algorithm works quite well for simple embedded systems because of its low overhead.

See also

References

  1. ^ "Real-time Operating Systems (RTOS)". Benzinga. 13 September 2023. Retrieved 13 September 2023.
  2. ^ "Response Time and Jitter". Archived from the original on 2011-07-23. Retrieved 2010-12-04.
  3. ^ Tanenbaum, Andrew (2008). Modern Operating Systems. Upper Saddle River, NJ: Pearson/Prentice Hall. p. 160. ISBN 978-0-13-600663-3.
  4. ^ "RTOS Concepts". Archived from the original on 2011-07-23. Retrieved 2010-12-04.
  5. ^ Samek, Miro (23 May 2023). "Programming embedded systems: RTOS – what is real-time?". Embedded.com. Retrieved 13 September 2023.
  6. ^ Phraner, Ralph A. (Fall 1984). "The Future of Unix on the IBM PC". Byte. pp. 59–64.
  7. ^ "CS 241, University of Illinois" (PDF).

Read other articles:

Edoardo Scotti Edoardo Scotti durante la prima frazione nella staffetta 4×400 m agli Europei di Berlino 2018 Nazionalità  Italia Altezza 184 cm Peso 70 kg Atletica leggera Specialità 400 metri piani Società  Carabinieri Record 200 m 2095 (2020) 300 m 3287 (2021) 400 m 4521 (2020) 400 m 4641 (indoor - 2022) 4×400 m 2'5881 (2021) CarrieraSocietà 2015-2016 Fanfulla Lodigiana2017-2018 CUS Parma2019- CarabinieriNazionale 2018- Italia9Palmarès Competizione Ori Argenti Bronzi Worl…

Indian tourist train Mahaparinirvan ExpressManufacturerIndian RailwaysBuilt atIntegral Coach Factory, ChennaiFamily nameLuxury TrainsConstructed2007Entered service2007OperatorsIndian Railways and Indian Railway Catering and Tourism Corporation (IRCTC)Lines servedHowrah–Gaya–Delhi line The Mahaparinirvan Express is a tourist train which was launched by the Indian Railway Catering and Tourism Corporation (IRCTC) on 28 March 2007, to attract Buddhist pilgrims.[1] The train takes passeng…

Not to be confused with Pixley ka Seme Local Municipality. District municipality in Northern Cape, South AfricaPixley ka SemeDistrict municipality SealLocation in South AfricaCoordinates: 30°30′S 23°30′E / 30.500°S 23.500°E / -30.500; 23.500CountrySouth AfricaProvinceNorthern CapeSeatDe AarLocal municipalities List UbuntuUmsobomvuEmthanjeniKareebergRenosterbergThembelihleSiyathembaSiyancuma Government[1] • TypeMunicipal council • Ma…

Questa voce o sezione sull'argomento televisione non cita le fonti necessarie o quelle presenti sono insufficienti. Puoi migliorare questa voce aggiungendo citazioni da fonti attendibili secondo le linee guida sull'uso delle fonti. Segui i suggerimenti del progetto di riferimento. La codifica a colori del sistema televisivo nel mondo. I paesi che utilizzano il sistema NTSC sono visualizzati in verde. L'NTSC è uno standard per la creazione, trasmissione e ricezione di contenuti video analog…

Largest burial mound in Chernihiv, Ukraine Black GraveЧорна могилаEngraved by Charles Laplante after Achille-Louis-Joseph Sirouy, 1880Location4 Proletarian Street, Chernihiv, Chernihiv Oblast, Ukraine[1]Coordinates51°30′N 31°20′E / 51.500°N 31.333°E / 51.500; 31.333TypeBurialArea2,300 square metres (25,000 sq ft)[citation needed]Volume7,666 cubic metres (10,027 cu yd)[citation needed]Circumference170 metres (5…

JoisellecomuneJoiselle – Veduta LocalizzazioneStato Francia RegioneGrand Est Dipartimento Marna ArrondissementÉpernay CantoneSézanne-Brie et Champagne TerritorioCoordinate48°46′N 3°31′E / 48.766667°N 3.516667°E48.766667; 3.516667 (Joiselle)Coordinate: 48°46′N 3°31′E / 48.766667°N 3.516667°E48.766667; 3.516667 (Joiselle) Superficie10 km² Abitanti89[1] (2009) Densità8,9 ab./km² Altre informazioniCod. postale51310 Fus…

1941 filmAjah BerdosaNewspaper adDirected byWu TsunStarring M Arief S Waldy Elly Joenara Soetijem CinematographyChok Chin HsienProductioncompanyStar FilmRelease date 1941 (1941) (Dutch East Indies) CountryDutch East IndiesLanguageMalay Ajah Berdosa (Perfected Spelling: Ayah Berdosa; Malay for The Sinful Father) is a likely-lost 1941 film from the Dutch East Indies (now Indonesia) directed by Wu Tsun for Star Film. Starring M. Arief, S Waldy, Elly Joenara, and Soetijem, it follows a vill…

Species of rodent Merriam's Kangaroo Rat Conservation status Least Concern  (IUCN 3.1)[1] Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Chordata Class: Mammalia Order: Rodentia Family: Heteromyidae Genus: Dipodomys Species: D. merriami Binomial name Dipodomys merriamiMearns, 1890 Subspecies Dipodomys merriami ambiguus Dipodomys merriami annulus Dipodomys merriami arenivagus Dipodomys merriami atronasus Dipodomys merriami brunensis Dipodomys merriami coll…

Samoyedic languages spoken in Russia Not to be confused with Enets language. Nenetsненэцяʼ вадаnenécja' vadaNative toRussiaRegionNenets Autonomous Okrug, Yamalo-Nenets Autonomous Okrug, Krasnoyarsk Krai, Komi Republic, Murmansk Oblast[citation needed]Ethnicity49,787 (2020 census)[1]Native speakers38,405 (2020 census)[2]Language familyUralic Samoyedic(core)Enets–NenetsNenetsDialects Forest Nenets Tundra Nenets Language codesISO 639-3yrkGlottolognene…

American artist, photographer, scientist, composer, and keyboardist Ned LaginBorn (1948-03-17) March 17, 1948 (age 76)OriginRoslyn Heights, New York, United StatesGenresElectronic, avant-garde, space music, jazz, classicalOccupation(s)Artist, Photographer, Scientist, Composer, KeyboardistInstrument(s)Piano, Electric Piano, Clavichord, Synthesizer, ComputerLabelsRound, United Artists, RykodiscWebsiteSpiritcats.comMusical artist Ned Lagin (born March 17, 1948) is an American artist, photograp…

لويس التاسع (بالفرنسية: Louis IX)‏[1]، و(بالفرنسية: Saint Louis)‏[1]  ملك فرنسا 1226 ← 1270 معلومات شخصية الميلاد 1214بواسي الوفاة 1270تونس سبب الوفاة زحار،  وبثع[2]  مكان الدفن كاتدرائية سان دوني  مواطنة مملكة فرنسا  الزوجة مارغريت بروفانس (27 مايو 1234–25 أغسطس 1270)  الأ…

Gettin' Tighter redirects here. For the song by Tom Robinson & the Voice Squad, see Getting Tighter. 1975 studio album by Deep PurpleCome Taste the BandStudio album by Deep PurpleReleased7 November 1975 (1975-11-07)[1][2]Recorded3 August – 1 September 1975StudioMusicland (Munich)Genre Hard rock funk rock[3] Length37:16LabelPurpleProducerMartin BirchDeep PurpleDeep Purple chronology Stormbringer(1974) Come Taste the Band(1975) Perfect Strangers…

Chronologies Données clés 1974 1975 1976  1977  1978 1979 1980Décennies :1940 1950 1960  1970  1980 1990 2000Siècles :XVIIIe XIXe  XXe  XXIe XXIIeMillénaires :-Ier Ier  IIe  IIIe Chronologies géographiques Afrique Afrique du Sud, Algérie, Angola, Bénin, Botswana, Burkina Faso, Burundi, Cameroun, Cap-Vert, République centrafricaine, Comores, République du Congo, République démocratique du Congo, Côte d'Ivoire, Djibouti, Égypte, …

1948 battle of the 1947–1949 Palestine War Battle of Mishmar HaEmekPart of the 1947–1948 civil war in Mandatory PalestineJewish soldiers at the entry of the Mishmar Ha'emek, 1948Date4–15 April 1948LocationMishmar HaEmek, Mandatory Palestine32°36′35″N 35°8′30″E / 32.60972°N 35.14167°E / 32.60972; 35.14167Result Yishuv victory Arab villages in the area occupiedBelligerents Haganah Arab Liberation ArmyCommanders and leaders Yitzhak Sadeh Fawzi al-QawuqjiStr…

Ancient Mesopotamian city Map of the Near East showing the extent of the Akkadian Empire and the general area in which Akkad was located Akkad (/ˈækæd/; also spelt Accad, Akkade, or Agade, Akkadian: 𒀀𒂵𒉈𒆠 akkadê, also 𒌵𒆠 URIKI in Sumerian during the Ur III period) was the capital of the Akkadian Empire, which was the dominant political force in Mesopotamia during a period of about 150 years in the last third of the 3rd millennium BC. Its location is unknown. In the early day…

2016 United States House of Representatives elections in New York ← 2014 November 8, 2016 (2016-11-08) 2018 → All 27 New York seats to the United States House of Representatives   Majority party Minority party   Party Democratic Republican Last election 18 9 Seats won 18 9 Seat change Popular vote 4,456,967 2,525,426 Percentage 62.81% 35.59% Swing 7.68% 7.06% Election results by seat changeElection results by districtResults:…

一中同表,是台灣处理海峡两岸关系问题的一种主張,認為中华人民共和国與中華民國皆是“整個中國”的一部份,二者因為兩岸現狀,在各自领域有完整的管辖权,互不隶属,同时主張,二者合作便可以搁置对“整个中國”的主权的争议,共同承認雙方皆是中國的一部份,在此基礎上走向終極統一。最早是在2004年由台灣大學政治学教授張亞中所提出,希望兩岸由一中各表的…

Village sign language in Thailand Ban Khor Sign Languageภาษามือบ้านค้อNative toThailandNative speakers400 (2009)[1]Language familysign language village signisolateBan Khor Sign LanguageLanguage codesISO 639-3bfkGlottologbank1251ELPBan Khor Sign Language Ban Khor Sign Language (BKSL; Thai: ภาษามือบ้านค้อ) is a village sign language used by at least 400 people of a rice-farming community in the village of Ban Khor in a remot…

We Were Soldiers - Fino all'ultimo uomoMel Gibson in una scena del filmTitolo originaleWe Were Soldiers Lingua originaleinglese Paese di produzioneStati Uniti d'America Anno2002 Durata138 minuti Rapporto2.39:1 Genereguerra, drammatico, azione RegiaRandall Wallace SoggettoHarold G. Moore, Joseph L. Galloway (libro) SceneggiaturaRandall Wallace ProduttoreRandall Wallace, Bruce Davey, Stephen McEveety Produttore esecutivoJim Lemley, Arne Schmidt Casa di produzioneParamount Pictures, Icon Pr…

Japanese supernatural entity Sokokuradani no Akaname (Akaname of the Deep Dark Valley), a frame on a picture print used as dice game board. Hyakushu kaibutsu yōkai sugoroku (1858) by Utagawa Yoshikazu [ja]. Akaname, Gazu hyakkiyagyō by Toriyama Sekien[1] The akaname (垢(あか)嘗(なめ), 'scum-licker'; 'filth-licker') is a Japanese yōkai depicted in Toriyama Sekien's 1776 book Gazu Hyakki Yagyō,[2][3] with its precursor or equivalent akaneburi (/垢ね…