Reentrancy (computing)

Reentrancy is a programming concept where a function or subroutine can be interrupted and then resumed before it finishes executing. This means that the function can be called again before it completes its previous execution. Reentrant code is designed to be safe and predictable when multiple instances of the same function are called simultaneously or in quick succession. A computer program or subroutine is called reentrant if multiple invocations can safely run concurrently on multiple processors, or if on a single-processor system its execution can be interrupted and a new execution of it can be safely started (it can be "re-entered"). The interruption could be caused by an internal action such as a jump or call, or by an external action such as an interrupt or signal, unlike recursion where new invocations can only be caused by internal call.

This definition originates from multiprogramming environments, where multiple processes may be active concurrently and where the flow of control could be interrupted by an interrupt and transferred to an interrupt service routine (ISR) or "handler" subroutine. Any subroutine used by the handler that could potentially have been executing when the interrupt was triggered should be reentrant. Similarly, code shared by two processors accessing shared data should be reentrant. Often, subroutines accessible via the operating system kernel are not reentrant. Hence, interrupt service routines are limited in the actions they can perform; for instance, they are usually restricted from accessing the file system and sometimes even from allocating memory.

Reentrancy is neither necessary nor sufficient for thread-safety in multi-threaded environments. In other words, a reentrant subroutine can be thread-safe,[1] but is not guaranteed to be[citation needed]. Conversely, thread-safe code need not be reentrant (see below for examples).

Other terms used for reentrant programs include "sharable code".[2] Reentrant subroutines are sometimes marked in reference material as being "signal safe".[3] Reentrant programs are often[a] "pure procedures".

Background

Reentrancy is not the same thing as idempotence, in which the function may be called more than once yet generate exactly the same output as if it had only been called once. Generally speaking, a function produces output data based on some input data (though both are optional, in general). Shared data could be accessed by any function at any time. If data can be changed by any function (and none keep track of those changes), there is no guarantee to those that share a datum that that datum is the same as at any time before.

Data has a characteristic called scope, which describes where in a program the data may be used. Data scope is either global (outside the scope of any function and with an indefinite extent) or local (created each time a function is called and destroyed upon exit).

Local data is not shared by any routines, re-entering or not; therefore, it does not affect re-entrance. Global data is defined outside functions and can be accessed by more than one function, either in the form of global variables (data shared between all functions), or as static variables (data shared by all invocations of the same function). In object-oriented programming, global data is defined in the scope of a class and can be private, making it accessible only to functions of that class. There is also the concept of instance variables, where a class variable is bound to a class instance. For these reasons, in object-oriented programming, this distinction is usually reserved for the data accessible outside of the class (public), and for the data independent of class instances (static).

Reentrancy is distinct from, but closely related to, thread-safety. A function can be thread-safe and still not reentrant. For example, a function could be wrapped all around with a mutex (which avoids problems in multithreading environments), but, if that function were used in an interrupt service routine, it could starve waiting for the first execution to release the mutex. The key for avoiding confusion is that reentrant refers to only one thread executing. It is a concept from the time when no multitasking operating systems existed.

Rules for reentrancy

Reentrant code may not hold any static or global non-constant data without synchronization.
Reentrant functions can work with global data. For example, a reentrant interrupt service routine could grab a piece of hardware status to work with (e.g., serial port read buffer) which is not only global, but volatile. Still, typical use of static variables and global data is not advised, in the sense that, except in sections of code that are synchronized, only atomic read-modify-write instructions should be used in these variables (it should not be possible for an interrupt or signal to come during the execution of such an instruction). Note that in C, even a read or write is not guaranteed to be atomic; it may be split into several reads or writes.[4] The C standard and SUSv3 provide sig_atomic_t for this purpose, although with guarantees only for simple reads and writes, not for incrementing or decrementing.[5] More complex atomic operations are available in C11, which provides stdatomic.h.
Reentrant code may not modify itself without synchronization.
The operating system might allow a process to modify its code. There are various reasons for this (e.g., blitting graphics quickly) but this generally requires synchronization to avoid problems with reentrancy.

It may, however, modify itself if it resides in its own unique memory. That is, if each new invocation uses a different physical machine code location where a copy of the original code is made, it will not affect other invocations even if it modifies itself during execution of that particular invocation (thread).

Reentrant code may not call non-reentrant computer programs or routines without synchronization.
Multiple levels of user, object, or process priority or multiprocessing usually complicate the control of reentrant code. It is important to keep track of any access or side effects that are done inside a routine designed to be reentrant.

Reentrancy of a subroutine that operates on operating-system resources or non-local data depends on the atomicity of the respective operations. For example, if the subroutine modifies a 64-bit global variable on a 32-bit machine, the operation may be split into two 32-bit operations, and thus, if the subroutine is interrupted while executing, and called again from the interrupt handler, the global variable may be in a state where only 32 bits have been updated. The programming language might provide atomicity guarantees for interruption caused by an internal action such as a jump or call. Then the function f in an expression like (global:=1) + (f()), where the order of evaluation of the subexpressions might be arbitrary in a programming language, would see the global variable either set to 1 or to its previous value, but not in an intermediate state where only part has been updated. (The latter can happen in C, because the expression has no sequence point.) The operating system might provide atomicity guarantees for signals, such as a system call interrupted by a signal not having a partial effect. The processor hardware might provide atomicity guarantees for interrupts, such as interrupted processor instructions not having partial effects.

Examples

To illustrate reentrancy, this article uses as an example a C utility function, swap(), that takes two pointers and transposes their values, and an interrupt-handling routine that also calls the swap function.

Neither reentrant nor thread-safe

This is an example swap function that fails to be reentrant or thread-safe. Since the tmp variable is globally shared, without synchronization, among any concurrent instances of the function, one instance may interfere with the data relied upon by another. As such, it should not have been used in the interrupt service routine isr():

int tmp;

void swap(int* x, int* y)
{
    tmp = *x;
    *x = *y;
    /* Hardware interrupt might invoke isr() here. */
    *y = tmp;    
}

void isr()
{
    int x = 1, y = 2;
    swap(&x, &y);
}

Thread-safe but not reentrant

The function swap() in the preceding example can be made thread-safe by making tmp thread-local. It still fails to be reentrant, and this will continue to cause problems if isr() is called in the same context as a thread already executing swap():

_Thread_local int tmp;

void swap(int* x, int* y)
{
    tmp = *x;
    *x = *y;
    /* Hardware interrupt might invoke isr() here. */
    *y = tmp;    
}

void isr()
{
    int x = 1, y = 2;
    swap(&x, &y);
}

Reentrant and thread-safe

An implementation of swap() that allocates tmp on the stack instead of globally and that is called only with unshared variables as parameters[b] is both thread-safe and reentrant. Thread-safe because the stack is local to a thread and a function acting just on local data will always produce the expected result. There is no access to shared data therefore no data race.

void swap(int* x, int* y)
{
    int tmp;
    tmp = *x;
    *x = *y;
    *y = tmp;    /* Hardware interrupt might invoke isr() here. */
}

void isr()
{
    int x = 1, y = 2;
    swap(&x, &y);
}

Reentrant interrupt handler

A reentrant interrupt handler is an interrupt handler that re-enables interrupts early in the interrupt handler. This may reduce interrupt latency.[6] In general, while programming interrupt service routines, it is recommended to re-enable interrupts as soon as possible in the interrupt handler. This practice helps to avoid losing interrupts.[7]

Further examples

In the following code, neither f nor g functions is reentrant.

int v = 1;

int f()
{
    v += 2;
    return v;
}

int g()
{
    return f() + 2;
}

In the above, f() depends on a non-constant global variable v; thus, if f() is interrupted during execution by an ISR which modifies v, then reentry into f() will return the wrong value of v. The value of v and, therefore, the return value of f, cannot be predicted with confidence: they will vary depending on whether an interrupt modified v during f's execution. Hence, f is not reentrant. Neither is g, because it calls f, which is not reentrant.

These slightly altered versions are reentrant:

int f(int i)
{
    return i + 2;
}

int g(int i)
{
    return f(i) + 2;
}

In the following, the function is thread-safe, but not (necessarily) reentrant:

int function()
{
    mutex_lock();

    // ...
    // function body
    // ...

    mutex_unlock();
}

In the above, function() can be called by different threads without any problem. But, if the function is used in a reentrant interrupt handler and a second interrupt arises inside the function, the second routine will hang forever. As interrupt servicing can disable other interrupts, the whole system could suffer.

Notes

  1. ^ A program that serializes self-modification may be reentrant, and a pure procedure that updates global data without proper serialization may fail to be reentrant.
  2. ^ If isr() called swap() with one or two global variables as parameters then swap() would not be reentrant

See also

References

  1. ^ Kerrisk 2010, p. 657.
  2. ^ Ralston 2000, p. 1514–1515.
  3. ^ "pthread_cond_init()--Initialize Condition Variable". IBM Knowledge Center. Retrieved 2019-10-05.
  4. ^ Preshing, Jeff (2013-06-18). "Atomic vs. Non-Atomic Operations". Preshing on Programming. Archived from the original on 2014-12-03. Retrieved 2018-04-24.
  5. ^ Kerrisk 2010, p. 428.
  6. ^ Sloss et al. 2004, p. 342.
  7. ^ Regehr, John (2006). "Safe and Structured Use of Interrupts in Real-time and Embedded Software" (PDF). Handbook of Real-Time and Embedded Systems. CRC Press. Archived (PDF) from the original on 2007-08-24 – via the author's website at the University of Utah School of Computing.

Works cited

Further reading

Read other articles:

Duta Besar Amerika Serikat untuk LibyaSegel Kementerian Dalam Negeri Amerika SerikatDicalonkan olehPresiden Amerika SerikatDitunjuk olehPresidendengan nasehat Senat Berikut ini adalah daftar Duta Besar Amerika Serikat untuk Libya Daftar Andrew Green Lynch Henry Serrano Villard John L. Tappin John Wesley Jones Edwin Allan Lightner David D. Newsom Joseph Palmer II Harold G. Josif Robert A. Stein Robert Carle William L. Eagleton Gregory L. Berry Charles O. Cecil Gene A. Cretz[1][2 ...

 

Artikel ini tidak memiliki referensi atau sumber tepercaya sehingga isinya tidak bisa dipastikan. Tolong bantu perbaiki artikel ini dengan menambahkan referensi yang layak. Tulisan tanpa sumber dapat dipertanyakan dan dihapus sewaktu-waktu.Cari sumber: Dodol Garut – berita · surat kabar · buku · cendekiawan · JSTOR Dodol Garut Dodol Garut adalah camilan yang berasal dari Kabupaten Garut, Jawa Barat. Pada umumnya produk Dodol Garut yang ada di pasaran m...

 

العلاقات المجرية البوليفية المجر بوليفيا   المجر   بوليفيا تعديل مصدري - تعديل   العلاقات المجرية البوليفية هي العلاقات الثنائية التي تجمع بين المجر وبوليفيا.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين: وجه المقارنة الم�...

University in Ghana All Nations UniversityAll Nations University College (ANUC) School of Engineering, Main Campus, Koforidua - Akwadum Highway.MottoEquipped for every good workTypePrivateEstablishedOctober 2002PresidentDr. Samuel DonkorLocationKoforidua, Eastern Region, Ghana6°05′26″N 0°15′48″W / 6.09056°N 0.26333°W / 6.09056; -0.26333Websitewww.anuc.edu.gh All Nations University was founded by Rev. Dr. Samuel Donkor in Ghana. It began with 37 students in ...

 

American politician (1864–1941) Willis C. HawleyMember of the U.S. House of Representativesfrom Oregon's 1st districtIn officeMarch 4, 1907 – March 3, 1933Preceded byBinger HermannSucceeded byJames W. Mott Personal detailsBornWillis Chatman Hawley(1864-05-05)May 5, 1864Monroe, OregonDiedJuly 24, 1941(1941-07-24) (aged 77)Salem, OregonPolitical partyRepublicanAlma materWillamette University Willis Chatman Hawley (May 5, 1864 – July 24, 1941) was an American politician an...

 

Fun and Fancy FreePoster filmSutradaraJack Kinney (animasi)Bill Roberts (animasi)Hamilton Luske (animasi)William MorganProduserWalt DisneyDitulis olehHomer BrightmanEldon DediniLance NolleyTom OrebHarry ReevesTed SearsSinclair Lewis (pencipta Bongo)PemeranCliff EdwardsEdgar BergenLuana PattenWalt DisneyClarence NashPinto ColvigBilly GilbertAnita GordonDinah ShoreDistributorRKO Radio PicturesTanggal rilis27 September 1947Durasi73 menitBahasaInggris Fun and Fancy Free adalah sebuah film yang di...

Questa voce o sezione sull'argomento chiese della Liguria 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. Santuario di Nostra Signora del GazzoVista frontale del Santuario del GazzoStato Italia RegioneLiguria LocalitàGenova Coordinate44°26′32″N 8°50′52″E / 44.442222°N 8.847778°E44.442222; 8.847778Coordinate: 44°26′32�...

 

Malaysian journalist In this Malay name, there is no surname or family name. The name Salim is a patronymic, and the person should be referred to by their given name, Abdul Rahim. Abdul Rahim KajaiPortrait of Abdul Rahim KajaiBornAbdul Rahim Haji Salim1894Setapak, Selangor, Federated Malay States (now Malaysia)Died5 December 1943(1943-12-05) (aged 48–49)Selangor, Japanese-occupied MalayaAlma materSetapak Malay SchoolOccupation(s)Typesetter, journalist, novelist, editorYears a...

 

Questa voce sull'argomento calciatori cecoslovacchi è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Segui i suggerimenti del progetto di riferimento. Zdeněk Šreiner Nazionalità  Cecoslovacchia Calcio Ruolo Centrocampista Termine carriera 1987 CarrieraSquadre di club1 1976-1987 Baník Ostrava OKD199+ (18+)Nazionale 1980-1984 Cecoslovacchia6 (0)Palmarès  Olimpiadi Oro Mosca 1980 1 I due numeri indicano le presenze e le reti segnate, p...

Северный морской котик Самец Научная классификация Домен:ЭукариотыЦарство:ЖивотныеПодцарство:ЭуметазоиБез ранга:Двусторонне-симметричныеБез ранга:ВторичноротыеТип:ХордовыеПодтип:ПозвоночныеИнфратип:ЧелюстноротыеНадкласс:ЧетвероногиеКлада:АмниотыКлада:Синапси...

 

Ji So-Yun지소연 Informasi pribadiNama lengkap Ji So-YunTanggal lahir 21 Februari 1991 (umur 33)Tempat lahir Seoul, Korea SelatanTinggi 161 m (528 ft 2+1⁄2 in)Posisi bermain GelandangInformasi klubKlub saat ini Chelsea LFCNomor 10Karier junior2006–2008 Dongsan Info & Industry HS2009–2010 Hanyang Women's CollegeKarier senior*Tahun Tim Tampil (Gol)2011–2013 INAC Kobe Leonessa 2014– Chelsea LFC Tim nasional‡2007–2008 U-17 Republik Korea ? (11)2007–2...

 

U.S. Centers for Disease Control and Prevention program Epidemic Intelligence ServiceAgency overviewFormedOctober 26, 1951; 72 years ago (1951-10-26)[1]HeadquartersAtlanta, Georgia, U.S.33°47′58″N 84°19′42″W / 33.79944°N 84.32833°W / 33.79944; -84.32833Employees60[2]Parent agencyCenters for Disease Control and PreventionWebsitewww.cdc.gov/eis/ The Epidemic Intelligence Service (EIS) is a program of the U.S. Centers for Dise...

Noriaki YuasaNoriaka Yuasa pada 1967Lahir(1933-09-28)28 September 1933Tokyo, JepangMeninggal14 Juni 2004(2004-06-14) (umur 70)JepangPekerjaanSutradara Noriaki Yuasa (湯浅 憲明code: ja is deprecated , Yuasa Noriaki) (28 September 1933 – 14 Juni 2004) adalah seorang sutradara Jepang. Yuasa adalah sutradara utama dari seri film Jepang Gamera, tentang seekor kura-kura raksasa yang berteman dengan anak-anak kecil dan bertarung melawan monster-monster raksasa.[1] S...

 

Town in County Durham, England This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Crook, County Durham – news · newspapers · books · scholar · JSTOR (December 2018) (Learn how and when to remove this message) Town in EnglandCrookTownHope StreetCrookLocation within County DurhamPopulation10,019 [1]O...

 

Australian musician and songwriter (born 1954) For the Australian journalist, see Phil Small (journalist). Phil SmallSmall with Cold Chisel in 2012Background informationBirth namePhillip James SmallBorn (1954-08-02) 2 August 1954 (age 69)Adelaide, South Australia, AustraliaGenresPub rockOccupation(s)Musician, songwriterInstrument(s)Bass, vocalsYears active1971–presentMusical artist Phillip James Small (born 2 August 1954) is an Australian musician and songwriter, who is the bass guitar...

This article includes a list of references, related reading, or external links, but its sources remain unclear because it lacks inline citations. Please help improve this article by introducing more precise citations. (August 2016) (Learn how and when to remove this message) Be 4/6 12302Be 4/6 number 12302 in the 1930sType and originPower typeElectricBuilderBrown, Boveri & Cie (BBC)Build date1919Total produced1SpecificationsConfiguration:​ • UIC(1’B)(B1’)Gauge1,435&...

 

1956 film Our Miss BrooksDirected byAl LewisWritten byAl LewisJoseph QuillanProduced byDavid WeisbartStarringEve ArdenGale GordonDon PorterRobert RockwellCinematographyJoseph LaShelleEdited byClarence KolsterFredrick Y. SmithMusic byRoy WebbProductioncompanyLute ProductionsDistributed byWarner Bros.Release date April 24, 1956 (1956-04-24) Running time85 minutesCountryUnited StatesLanguageEnglish Our Miss Brooks is a 1956 American comedy film starring Eve Arden,[1][2...

 

КоммунаШапоChapeau 46°29′19″ с. ш. 3°31′26″ в. д.HGЯO Страна  Франция Регион Овернь Департамент Алье Кантон Нёйи-ле-Реаль Мэр Pierre Brenon(2008–2014) История и география Площадь 33,42 км² Высота центра 239–285 м Часовой пояс UTC+1:00, летом UTC+2:00 Население Население 223 человека (2008) Пл...

Waterfall on Hunlen Creek in Tweedsmuir South Provincial Park, British Columbia, Canada Hunlen FallsLocationTweedsmuir South Provincial Park, British Columbia, CanadaCoordinates52°16′36″N 125°46′21″W / 52.2768°N 125.7724°W / 52.2768; -125.7724[1]TypePlungeTotal height260 m (850 ft)Number of drops1Longest drop260 m (850 ft)Total width24 m (79 ft)Average width30 m (98 ft)Run15 m (49 ft)WatercourseHunle...

 

Cyrenaic presbyter and founder of Arianism (died 336) For other uses, see Arius (disambiguation). AriusArius arguing for the supremacy of God the Father, and that the Son had a beginning as a true FirstbornBorn256Ptolemais, Cyrenaica, Roman Empire(modern-day Tolmeita, Libya)Died336 (aged 80)Constantinople, Thracia, Roman Empire(modern-day Istanbul, Turkey)OccupationPresbyterNotable workThaliaTheological workEra3rd and 4th centuries ADLanguageKoine GreekTradition or movementArianismNotable ide...