Event loop

In computer science, the event loop (also known as message dispatcher, message loop, message pump, or run loop) is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by making a request to some internal or external "event provider" (that generally blocks the request until an event has arrived), then calls the relevant event handler ("dispatches the event").

It is also commonly implemented in servers such as web servers.

The event-loop may be used in conjunction with a reactor, if the event provider follows the file interface, which can be selected or 'polled' (the Unix system call, not actual polling). The event loop almost always operates asynchronously with the message originator.

When the event loop forms the central control flow construct of a program, as it often does, it may be termed the main loop or main event loop. This title is appropriate, because such an event loop is at the highest level of control within the program.

Message passing

Message pumps are said to 'pump' messages from the program's message queue (assigned and usually owned by the underlying operating system) into the program for processing. In the strictest sense, an event loop is one of the methods for implementing inter-process communication. In fact, message processing exists in many systems, including a kernel-level component of the Mach operating system. The event loop is a specific implementation technique of systems that use message passing.

Alternative designs

This approach is in contrast to a number of other alternatives:

  • Traditionally, a program simply ran once, then terminated. This type of program was very common in the early days of computing, and lacked any form of user interactivity. This is still used frequently, particularly in the form of command-line-driven programs. Any parameters are set up in advance and passed in one go when the program starts.
  • Menu-driven designs. These still may feature a main loop, but are not usually thought of as event driven in the usual sense.[citation needed] Instead, the user is presented with an ever-narrowing set of options until the task they wish to carry out is the only option available. Limited interactivity through the menus is available.

Usage

Due to the predominance of graphical user interfaces, most modern applications feature a main loop. The get_next_message() routine is typically provided by the operating system, and blocks until a message is available. Thus, the loop is only entered when there is something to process.

function main
    initialize()
    while message != quit
        message := get_next_message()
        process_message(message)
    end while
end function

File interface

Under Unix, the "everything is a file" paradigm naturally leads to a file-based event loop. Reading from and writing to files, inter-process communication, network communication, and device control are all achieved using file I/O, with the target identified by a file descriptor. The select and poll system calls allow a set of file descriptors to be monitored for a change of state, e.g. when data becomes available to be read.

For example, consider a program that reads from a continuously updated file and displays its contents in the X Window System, which communicates with clients over a socket (either Unix domain or Berkeley):

def main():
    file_fd = open("logfile.log")
    x_fd = open_display()
    construct_interface()
    while True:
        rlist, _, _ = select.select([file_fd, x_fd], [], []):
        if file_fd in rlist:
            data = file_fd.read()
            append_to_display(data)
            send_repaint_message()
        if x_fd in rlist:
            process_x_messages()

Handling signals

One of the few things in Unix that does not conform to the file interface are asynchronous events (signals). Signals are received in signal handlers, small, limited pieces of code that run while the rest of the task is suspended; if a signal is received and handled while the task is blocking in select(), select will return early with EINTR; if a signal is received while the task is CPU bound, the task will be suspended between instructions until the signal handler returns.

Thus an obvious way to handle signals is for signal handlers to set a global flag and have the event loop check for the flag immediately before and after the select() call; if it is set, handle the signal in the same manner as with events on file descriptors. Unfortunately, this gives rise to a race condition: if a signal arrives immediately between checking the flag and calling select(), it will not be handled until select() returns for some other reason (for example, being interrupted by a frustrated user).

The solution arrived at by POSIX is the pselect() call, which is similar to select() but takes an additional sigmask parameter, which describes a signal mask. This allows an application to mask signals in the main task, then remove the mask for the duration of the select() call such that signal handlers are only called while the application is I/O bound. However, implementations of pselect() have not always been reliable; versions of Linux prior to 2.6.16 do not have a pselect() system call,[1] forcing glibc to emulate it via a method prone to the very same race condition pselect() is intended to avoid.

An alternative, more portable solution, is to convert asynchronous events to file-based events using the self-pipe trick,[2] where "a signal handler writes a byte to a pipe whose other end is monitored by select() in the main program".[3] In Linux kernel version 2.6.22, a new system call signalfd() was added, which allows receiving signals via a special file descriptor.

Implementations

HTML/JavaScript

A web page and its JavaScript typically run in a single-threaded web browser process. The browser process deals with messages from a queue one at a time. A JavaScript function or another browser event might be associated with a given message. When the browser process has finished with a message, it proceeds to the next message in the queue.

Windows applications

On the Microsoft Windows operating system, a process that interacts with the user must accept and react to incoming messages, which is almost inevitably done by a message loop in that process. In Windows, a message is equated to an event created and imposed upon the operating system. An event can be user interaction, network traffic, system processing, timer activity, inter-process communication, among others. For non-interactive, I/O only events, Windows has I/O completion ports. I/O completion port loops run separately from the Message loop, and do not interact with the Message loop out of the box.

The "heart" of most Win32 applications is the WinMain() function, which calls GetMessage() in a loop. GetMessage() blocks until a message, or "event", is received (with function PeekMessage() as a non-blocking alternative). After some optional processing, it will call DispatchMessage(), which dispatches the message to the relevant handler, also known as WindowProc. Normally, messages that have no special WindowProc() are dispatched to DefWindowProc, the default one. DispatchMessage() calls the WindowProc of the HWND handle of the message (registered with the RegisterClass() function).

Message ordering

More recent versions of Microsoft Windows guarantee to the programmer that messages will be delivered to an application's message loop in the order that they were perceived by the system and its peripherals. This guarantee is essential when considering the design consequences of multithreaded applications.

However, some messages have different rules, such as messages that are always received last, or messages with a different documented priority.[4]

X Window System

Xlib event loop

X applications using Xlib directly are built around the XNextEvent family of functions; XNextEvent blocks until an event appears on the event queue, whereupon the application processes it appropriately. The Xlib event loop only handles window system events; applications that need to be able to wait on other files and devices could construct their own event loop from primitives such as ConnectionNumber, but in practice tend to use multithreading.

Very few programs use Xlib directly. In the more common case, GUI toolkits based on Xlib usually support adding events. For example, toolkits based on Xt Intrinsics have XtAppAddInput() and XtAppAddTimeout().

Please note that it is not safe to call Xlib functions from a signal handler, because the X application may have been interrupted in an arbitrary state, e.g. within XNextEvent. See [1] for a solution for X11R5, X11R6 and Xt.

GLib event loop

The GLib event loop was originally created for use in GTK but is now used in non-GUI applications as well, such as D-Bus. The resource polled is the collection of file descriptors the application is interested in; the polling block will be interrupted if a signal arrives or a timeout expires (e.g. if the application has specified a timeout or idle task). While GLib has built-in support for file descriptor and child termination events, it is possible to add an event source for any event that can be handled in a prepare-check-dispatch model.[2]

Application libraries that are built on the GLib event loop include GStreamer and the asynchronous I/O methods of GnomeVFS, but GTK remains the most visible client library. Events from the windowing system (in X, read off the X socket) are translated by GDK into GTK events and emitted as GLib signals on the application's widget objects.

macOS Core Foundation run loops

Exactly one CFRunLoop is allowed per thread, and arbitrarily many sources and observers can be attached. Sources then communicate with observers through the run loop, with it organising queueing and dispatch of messages.

The CFRunLoop is abstracted in Cocoa as an NSRunLoop, which allows any message (equivalent to a function call in non-reflective runtimes) to be queued for dispatch to any object.

See also

References

  1. ^ "Linux_2_6_16 - Linux Kernel Newbies". kernelnewbies.org. Retrieved 2021-03-03.
  2. ^ D. J. Bernstein. "The self-pipe trick".
  3. ^ BUGS, pselect(2): synchronous I/O multiplexing – Linux Programmer's Manual – System Calls
  4. ^ GetMessage() function with message priority list.

Read other articles:

Mercury-Atlas 7 (MA-7) Mercury MA-7 is de vierde bemande ruimtevlucht in het kader van het Amerikaanse Mercury programma. De capsule genaamd Aurora 7 werd gelanceerd met een Atlas raket. Scott Carpenter vloog drie maal rond de aarde. Bij de landing raakte de capsule enigszins uit koers, waardoor de capsule zo'n 400 km naast de beoogde plek terechtkwam. vluchtgegevens: lancering: tijd: 24 mei 1962 12:45 GMT plaats: Cape Canaveral Air Force Station, Verenigde Staten (lanceercomplex LC14) landin...

Cet article est une ébauche concernant les Jeux olympiques. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Article principal : Jeux olympiques d'été de 2016. 6 août - 7 août - 8 août Le dimanche 7 août aux Jeux olympiques d'été de 2016 est le cinquième jour de compétition. Faits marquants En raison du vent et des vives polémiques du jour précédent, les courses d'aviron du 7 août 2016 sont plu...

Asrul Sani Asrul Sani (lahir 21 Maret 1975) adalah seorang birokrat Indonesia kelahiran Watampone. Ia merupakan birokrat di Pemerintahan Provinsi Sulawesi Selatan selaku Kepala Dinas Penanaman Modal dan PTSP Sulsel. Pada 2013, ia ditugaskan sebagai Kepala Sub Bagian Tata Usaha. Pada 2017, ia ditugaskan menjadi Kasub Pelaksanaan dan Pengadaan Barang dan Jasa 2017. Pada 2020, ia diangkat menjadi Kepala Bagian Pengelolaan Layanan dan Pengadaan Secara Elektronik Setda Pemprov Sulsel. Pada 2021, i...

No debe confundirse con Remix OS. Resurrection Remix OS Parte de Android Información generalTipo de programa sistema operativo móvilDesarrollador Altan KRK (westcrip)Modelo de desarrollo Software libre y de código abiertoLanzamiento inicial 2012Licencia Apache License 2.0Estado actual En desarrolloIdiomas MultilenguajeInformación técnicaProgramado en CC++JavaTipo de núcleo Monolítico (Núcleo Linux modificado)Plataformas admitidas ARM, ARM64Método de actualización OTAVersionesÚltima...

Johan de Meester kan verwijzen naar: Johan de Meester (schrijver) (1860-1931) Johan de Meester jr., zijn zoon, toneelregisseur (1897-1986) Bekijk alle artikelen waarvan de titel begint met Johan de Meester of met Johan de Meester in de titel. Dit is een doorverwijspagina, bedoeld om de verschillen in betekenis of gebruik van Johan de Meester inzichtelijk te maken. Op deze pagina staat een uitleg van de verschillende betekenissen van Johan de Meester en verwijzingen da...

1958 film by Vincente Minnelli For the Broadway musical, see Gigi (musical). GigiTheatrical release posterDirected byVincente MinnelliScreenplay byAlan Jay LernerBased onGigi1944 novellaby ColetteProduced byArthur FreedStarringLeslie CaronMaurice ChevalierLouis JourdanHermione GingoldEva GaborJacques BergeracIsabel JeansCinematographyJoseph RuttenbergEdited byAdrienne FazanMusic byFrederick LoeweMusic adapted and conducted byAndré PrevinDistributed byMetro-Goldwyn-MayerRelease date May ...

يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. (مارس 2019) كأس السوبر الإيطالي 2017الحدثكأس السوبر الإيطالي يوفنتوس لاتسيو الدوري الإيطالي كأس إيطاليا 2 3 التاريخ13 أغس...

منتخب جبل طارق لكرة السلة التصنيف 147 ▲ 1 (16 سبتمبر 2019)[1] انضم للاتحاد الدولي 1985 البلد جبل طارق  بطولة المنطقة2 المشاركة 16 المشاركات الدولية أول مباراة  جمهورية أيرلندا 114–59 جبل طارق (تاكالي، مالطا; 14 ديسمبر 1988) أكبر فوز جبل طارق 102–51 جزيرة مان (فيسبي، السويد; 27 يونيو 201...

Mexico City metro station For the New York City Subway station, see Jamaica–179th Street station. JamaicaSTC Rapid transitView of westbound platform of Metro Jamaica line 9 portionGeneral informationLocationVenustiano CarranzaMexico CityMexicoCoordinates19°24′32.414″N 99°7′19.816″W / 19.40900389°N 99.12217111°W / 19.40900389; -99.12217111Owned byMexico City MetroOperated bySistema de Transporte Colectivo (STC)Line(s) (Martín Carrera – Santa Anita) (Tac...

Protein-coding gene in the species Homo sapiens BLCAPIdentifiersAliasesBLCAP, BC10, bladder cancer associated protein, apoptosis inducing factor, BLCAP apoptosis inducing factorExternal IDsOMIM: 613110 MGI: 1858907 HomoloGene: 38217 GeneCards: BLCAP Gene location (Human)Chr.Chromosome 20 (human)[1]Band20q11.23Start37,492,472 bp[1]End37,527,931 bp[1]Gene location (Mouse)Chr.Chromosome 2 (mouse)[2]Band2 H1|2 78.4 cMStart157,398,282 bp[2]End157,413,19...

English motorcycle racer (1939–2022) For other people with similar names, see Phil Reid. Phil ReadMBERead in 1968NationalityBritishBorn(1939-01-01)1 January 1939Luton, Bedfordshire, EnglandDied6 October 2022(2022-10-06) (aged 83)Canterbury, England Motorcycle racing career statistics Grand Prix motorcycle racingActive years1961 – 1976 First race1961 350cc Isle of Man TTLast race1976 500cc Nations Grand PrixFirst win1961 350cc Isle of Man TTLast win1975 500cc Czechoslovakian Grand Pri...

De Oude en Nieuwe Struiten is een voormalige Nederlandse gemeente die in 1855 bij Nieuw-Helvoet werd toegevoegd. De naam van het winkelcentrum in Hellevoetsluis genaamd de Struytse Hoeck, de wijk de Struyten en de Struytse Zeedijk herinneren hier nog aan. Oude en Nieuwe Struiten 1697 Zie ook Oude en Nieuwe Struijten (waterschap) Lijst van burgemeesters van Oude en Nieuwe Struiten Afbeeldingen De Struytse Zeedijk Oude en Nieuwe Struiten maakte deel uit van de gemeente Nieuw-Helvoet Wapen Media...

2010 Indian comedy movie Khichdi: The MovieTheatrical release posterDirected byAatish KapadiaStory byAatish KapadiaBased onKhichdi and Instant Khichdiby Aatish KapadiaProduced byJamnadas MajethiaStarringSupriya PathakAnang DesaiRajeev MehtaJamnadas MajethiaNimisha VakhariaNarrated byKesar MajethiaMarkand SoniCinematographySanjay JadhavEdited byHemal KothariMusic byRaju SinghProductioncompanyHats Off ProductionsDistributed byFox Star StudiosRelease date 1 October 2010 (2010-10-0...

Maritime subsidiary of the Loblaw Companies Atlantic SuperstoreTypeSupermarketIndustryRetailFounded1986; 37 years ago (1986)Headquarters3711 Joseph Howe DriveHalifax, Nova ScotiaB3L 4H8ProductsBakery, beer, charcuterie, clothing, dairy, deli, electronics (select locations), frozen foods, gardening centre, gasoline (select locations), general grocery, general merchandise, liquor, meat & poultry, pharmacy, photolab, produce, seafood, snacks, wineParentLoblaw CompaniesWebsi...

Professional cardioid dynamic microphone An SM58 Robert Lockwood, Jr using an SM58 in 1982 Patti Smith using an SM58 in 2007 Randall Bramblett using an SM58 in 2015 The Shure SM58 is a professional cardioid dynamic microphone, commonly used in live vocal applications. Produced since 1966 by Shure Incorporated, it has built a reputation among musicians for its durability and sound, and is still the industry standard for live vocal performance microphones.[1][2][3] The S...

1957–58 war between Morocco and Spain 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: Ifni War – news · newspapers · books · scholar · JSTOR (October 2012) (Learn how and when to remove this template message) Ifni WarPart of the Decolonisation of AfricaBorders of the Ifni territory before and after the war...

Peta menunjukkan lokasi Cuyapo Data sensus penduduk di Cuyapo Tahun Populasi Persentase 199549.791—200051.3660.67%200755.4561.06% Cuyapo adalah munisipalitas yang terletak di provinsi Nueva Ecija, Filipina. Pada tahun 2010, munisipalitas ini memiliki populasi sebesar 57.733 jiwa dan 12.831 rumah tangga. Pembagian wilayah Secara administratif Cuyapo terbagi menjadi 52 barangay, yaitu: Baloy Bambanaba Bantug Bentigan Bibiclat Bonifacio Bued Bulala Burgos Cabileo Cabangaran Cabatuan Cacapasan ...

Cerwil Klasifikasi ilmiah Kerajaan: Plantae Upakerajaan: Trachaeophyta Divisi: Magnoliophyta Kelas: Magnoliopsida Ordo: Apiales Famili: Apiaceae Genus: Anthriscus Spesies: A. cerefolium Nama binomial Anthriscus cerefolium(L.) Hoffm.[1] Sinonim[2] Anthriscus chaerophyllus St.-Lag. Anthriscus longirostris Bertol. Anthriscus sativa Besser Anthriscus trachysperma Rchb. ex Nyman Cerefolium sativum Besser Cerefolium sylvestre Besser Cerefolium trichospermum Besser Chaerefolium ...

Questa voce sull'argomento esoterismo è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Ciondolo-reliquiario del IX secolo che secondo la leggenda sarebbe un talismano appartenuto a Carlo Magno, oggi conservato nel Palazzo del Tau a Reims (Francia) Un talismano è un oggetto, solitamente di piccole dimensioni, a cui vengono attribuite proprietà magiche, propiziatorie e portafortuna. Il talismano, pertanto, non è da confondere con l'amuleto, che ha piut...

Vous lisez un « bon article » labellisé en 2008. Pour les articles homonymes, voir Nice (homonymie). Nice De haut en bas, et de gauche à droite : le quartier d'affaires du Grand Arénas, l'opéra de Nice, l'observatoire de Nice, la cathédrale Saint-Nicolas, vue panoramique d'une partie de la ville depuis la colline du château, l'hôtel Negresco, l'Allianz Riviera, les studios de la Victorine, la ligne 2 du tramway. Blason Logo Administration Pays France Région Provence-A...