Software transactional memory

In computer science, software transactional memory (STM) is a concurrency control mechanism analogous to database transactions for controlling access to shared memory in concurrent computing. It is an alternative to lock-based synchronization. STM is a strategy implemented in software, rather than as a hardware component. A transaction in this context occurs when a piece of code executes a series of reads and writes to shared memory. These reads and writes logically occur at a single instant in time; intermediate states are not visible to other (successful) transactions. The idea of providing hardware support for transactions originated in a 1986 paper by Tom Knight.[1] The idea was popularized by Maurice Herlihy and J. Eliot B. Moss.[2] In 1995, Nir Shavit and Dan Touitou extended this idea to software-only transactional memory (STM).[3] Since 2005, STM has been the focus of intense research[4] and support for practical implementations is growing.

Performance

Unlike the locking techniques used in most modern multithreaded applications, STM is often very optimistic: a thread completes modifications to shared memory without regard for what other threads might be doing, recording every read and write that it is performing in a log. Instead of placing the onus on the writer to make sure it does not adversely affect other operations in progress, it is placed on the reader, who after completing an entire transaction verifies that other threads have not concurrently made changes to memory that it accessed in the past. This final operation, in which the changes of a transaction are validated and, if validation is successful, made permanent, is called a commit. A transaction may also abort at any time, causing all of its prior changes to be rolled back or undone. If a transaction cannot be committed due to conflicting changes, it is typically aborted and re-executed from the beginning until it succeeds.

The benefit of this optimistic approach is increased concurrency: no thread needs to wait for access to a resource, and different threads can safely and simultaneously modify disjoint parts of a data structure that would normally be protected under the same lock.

However, in practice, STM systems also suffer a performance hit compared to fine-grained lock-based systems on small numbers of processors (1 to 4 depending on the application). This is due primarily to the overhead associated with maintaining the log and the time spent committing transactions. Even in this case performance is typically no worse than twice as slow.[5] Advocates of STM believe this penalty is justified by the conceptual benefits of STM.[citation needed]

Theoretically, the worst case space and time complexity of n concurrent transactions is O(n). Actual needs depend on implementation details (one can make transactions fail early enough to avoid overhead), but there will also be cases, albeit rare, where lock-based algorithms have better time complexity than software transactional memory.

Conceptual advantages and disadvantages

In addition to their performance benefits,[citation needed] STM greatly simplifies conceptual understanding of multithreaded programs and helps make programs more maintainable by working in harmony with existing high-level abstractions such as objects and modules. Lock-based programming has a number of well-known problems that frequently arise in practice:

  • Locking requires thinking about overlapping operations and partial operations in distantly separated and seemingly unrelated sections of code, a task which is very difficult and error-prone.
  • Locking requires programmers to adopt a locking policy to prevent deadlock, livelock, and other failures to make progress. Such policies are often informally enforced and fallible, and when these issues arise they are insidiously difficult to reproduce and debug.
  • Locking can lead to priority inversion, a phenomenon where a high-priority thread is forced to wait for a low-priority thread holding exclusive access to a resource that it needs.

In contrast, the concept of a memory transaction is much simpler, because each transaction can be viewed in isolation as a single-threaded computation. Deadlock and livelock are either prevented entirely or handled by an external transaction manager; the programmer need hardly worry about it. Priority inversion can still be an issue, but high-priority transactions can abort conflicting lower priority transactions that have not already committed.

However, the need to retry and abort transactions limits their behavior. Any operation performed within a transaction must be idempotent since a transaction might be retried. Additionally, if an operation has side effects that must be undone if the transaction is aborted, then a corresponding rollback operation must be included. This makes many input/output (I/O) operations difficult or impossible to perform within transactions. Such limits are typically overcome in practice by creating buffers that queue up the irreversible operations and perform them after the transaction succeeds. In Haskell, this limit is enforced at compile time by the type system.

Composable operations

In 2005, Tim Harris, Simon Marlow, Simon Peyton Jones, and Maurice Herlihy described an STM system built on Concurrent Haskell that enables arbitrary atomic operations to be composed into larger atomic operations, a useful concept impossible with lock-based programming. To quote the authors:

Perhaps the most fundamental objection [...] is that lock-based programs do not compose: correct fragments may fail when combined. For example, consider a hash table with thread-safe insert and delete operations. Now suppose that we want to delete one item A from table t1, and insert it into table t2; but the intermediate state (in which neither table contains the item) must not be visible to other threads. Unless the implementor of the hash table anticipates this need, there is simply no way to satisfy this requirement. [...] In short, operations that are individually correct (insert, delete) cannot be composed into larger correct operations.
—Tim Harris et al., "Composable Memory Transactions", Section 2: Background, pg.2[6]

With STM, this problem is simple to solve: simply wrapping two operations in a transaction makes the combined operation atomic. The only sticking point is that it is unclear to the caller, who is unaware of the implementation details of the component methods, when it should attempt to re-execute the transaction if it fails. In response, the authors proposed a retry command which uses the transaction log generated by the failed transaction to determine which memory cells it read, and automatically retries the transaction when one of these cells is modified, based on the logic that the transaction will not behave differently until at least one such value is changed.

The authors also proposed a mechanism for composition of alternatives, the orElse function. It runs one transaction and, if that transaction does a retry, runs a second one. If both retry, it tries them both again as soon as a relevant change is made.[clarification needed] This facility, comparable to features such as the Portable Operating System Interface (POSIX) networking select() call, allows the caller to wait on any one of a number of events simultaneously. It also simplifies programming interfaces, for example by providing a simple mechanism to convert between blocking and nonblocking operations.

This scheme has been implemented in the Glasgow Haskell Compiler.

Proposed language support

The conceptual simplicity of STMs enables them to be exposed to the programmer using relatively simple language syntax. Tim Harris and Keir Fraser's "Language Support for Lightweight Transactions" proposed the idea of using the classical conditional critical region (CCR) to represent transactions. In its simplest form, this is just an "atomic block", a block of code which logically occurs at a single instant:

// Insert a node into a doubly linked list atomically
atomic {
    newNode->prev = node;
    newNode->next = node->next;
    node->next->prev = newNode;
    node->next = newNode;
}

When the end of the block is reached, the transaction is committed if possible, or else aborted and retried. (This is simply a conceptual example, not correct code. For example, it behaves incorrectly if node is deleted from the list during the transaction.)

CCRs also permit a guard condition, which enables a transaction to wait until it has work to do:

atomic (queueSize > 0) {
    remove item from queue and use it
}

If the condition is not satisfied, the transaction manager will wait until another transaction has made a commit that affects the condition before retrying. This loose coupling between producers and consumers enhances modularity compared to explicit signaling between threads. "Composable Memory Transactions"[6] took this a step farther with its retry command (discussed above), which can, at any time, abort the transaction and wait until some value previously read by the transaction is modified before retrying. For example:

atomic {
    if (queueSize > 0) {
        remove item from queue and use it
    } else {
        retry
    }
}

This ability to retry dynamically late in the transaction simplifies the programming model and opens up new possibilities.

One issue is how exceptions behave when they propagate outside of transactions. In "Composable Memory Transactions",[6] the authors decided that this should abort the transaction, since exceptions normally indicate unexpected errors in Concurrent Haskell, but that the exception could retain information allocated by and read during the transaction for diagnostic purposes. They stress that other design decisions may be reasonable in other settings.

Transactional locking

STM can be implemented as a lock-free algorithm or it can use locking.[7] There are two types of locking schemes: In encounter-time locking (Ennals, Saha, and Harris), memory writes are done by first temporarily acquiring a lock for a given location, writing the value directly, and logging it in the undo log. Commit-time locking locks memory locations only during the commit phase.

A commit-time scheme named "Transactional Locking II" implemented by Dice, Shalev, and Shavit uses a global version clock. Every transaction starts by reading the current value of the clock and storing it as the read-version. Then, on every read or write, the version of the particular memory location is compared to the read-version; and, if it is greater, the transaction is aborted. This guarantees that the code is executed on a consistent snapshot of memory. During commit, all write locations are locked, and version numbers of all read and write locations are re-checked. Finally, the global version clock is incremented, new write values from the log are written back to memory and stamped with the new clock version.

Implementation issues

One problem with implementing software transactional memory with optimistic reading is that it is possible for an incomplete transaction to read inconsistent state (that is, to read a mixture of old and new values written by another transaction). Such a transaction is doomed to abort if it ever tries to commit, so this does not violate the consistency condition enforced by the transactional system, but it is possible for this "temporary" inconsistent state to cause a transaction to trigger a fatal exceptional condition such as a segmentation fault or even enter an endless loop, as in the following contrived example from Figure 4 of "Language Support for Lightweight Transactions":

atomic {
    if (x != y)
        while (true) { 
        }
}
atomic {
    x++;
    y++;
}
Transaction A
Transaction B

Provided x=y initially, neither transaction above alters this invariant, but it is possible that transaction A will read x after transaction B updates it but read y before transaction B updates it, causing it to enter an infinite loop. The usual strategy for dealing with this is to intercept any fatal exceptions and abort any transaction that is not valid.

One way to deal with these issues is to detect transactions that execute illegal operations or fail to terminate and abort them cleanly; another approach is the transactional locking scheme.

Practical implementations

References

  1. ^ Tom Knight. An architecture for mostly functional languages. Proceedings of the 1986 ACM conference on Lisp and functional programming.
  2. ^ Maurice Herlihy and J. Eliot B. Moss. Transactional memory: architectural support for lock-free data structures. Proceedings of the 20th annual international symposium on Computer architecture (ISCA '93). Volume 21, Issue 2, May 1993.
  3. ^ Nir Shavit and Dan Touitou. Software transactional memory. Distributed Computing. Volume 10, Number 2. February 1997.
  4. ^ ""software transactional memory" - Google Scholar". Retrieved 10 November 2013.
  5. ^ Peyton Jones, Simon. "Programming in the Age of Concurrency: Software Transactional Memory". Microsoft Developers Network: Channel 9. Retrieved 2007-06-09.
  6. ^ a b c Harris, T.; Marlow, S.; Peyton Jones, S.; Herlihy, M. (2005). "Composable memory transactions" (PDF). Proceedings of the tenth ACM SIGPLAN symposium on Principles and practice of parallel programming - PPoPP '05. p. 48. doi:10.1145/1065944.1065952. ISBN 1595930809. S2CID 53245159.
  7. ^ Concurrency_control#Methods
  8. ^ "Glasgow Haskell Compiler (GHC) Commentary: Software Transactional Memory (STM)". Haskell.org: GitLab.
  9. ^ "Software Transactional Memory in C++: Pure Functional Approach (tutorial)". GitHub.
  10. ^ "Refs and Transactions". Clojure.org.
  11. ^ "Poor man's STM in Node.js". Clojure.org.
  12. ^ "talhof8/kashmir". GitHub.
  13. ^ "Rust Package Registry". Crates.io.
  14. ^ "Introduction to Software Transactional Memory ZIO". Zio.dev.
  15. ^ "Kcas — STM based on lock-free MCAS". GitHub.
  16. ^ "Transactional memory (STM)". arrow-kt.io.

Read other articles:

Pertempuran TorgauBagian dari Perang Schlesien Ketiga (Perang Tujuh Tahun)Friedrich yang Agung selepas Torgau, oleh Bernhard RodeTanggal3 November 1760LokasiSüptitzer Höhen, di dekat Torgau, Sachsen, Kekaisaran Romawi Suci51°34′30″N 12°55′30″E / 51.57500°N 12.92500°E / 51.57500; 12.92500Koordinat: 51°34′30″N 12°55′30″E / 51.57500°N 12.92500°E / 51.57500; 12.92500Hasil Kemenangan PrusiaPihak terlibat Prusia AustriaTokoh ...

 

NorwegiaJulukanLøvene (Singa-Singa)AsosiasiNorges Fotballforbund (NFF)KonfederasiUEFA (Eropa)PelatihStåle SolbakkenKaptenMartin ØdegaardPenampilan terbanyakJohn Arne Riise (110)Pencetak gol terbanyakJørgen Juve (33)Stadion kandangUllevaal StadionKode FIFANORPeringkat FIFATerkini 46 2 (15 Februari 2024)[1]Tertinggi2 (Oktober 1993, Juli–Agustus 1995)Terendah88 (Juli 2017)Peringkat EloTerkini 34 3 (19 Januari 2024)[2] Warna pertama Warna kedua Pertandingan internasional per...

 

Titus O'NeilO'Neil di bulan April 2015Nama lahirThaddeus Michael BullardLahir29 April 1977 (umur 46)Boynton Beach, Florida,Amerika Serikat[1]Alma materUniversity of FloridaAnak2Karier gulat profesionalNama ringTitus O'Neil[2]Rufus PattersonTinggi6 ft 4 in (1,93 m)[2]Berat270 pon (120 kg)[2]Asal dariLive Oak, Florida[2]Tampa, Florida[3]Dilatih olehFlorida Championship WrestlingDebut2009[4] Thaddeus Michael Bu...

Fictional pirate For other uses, see Captain Hook (disambiguation). Fictional character Captain James HookPeter Pan character1912 illustration by Francis Donkin BedfordFirst appearancePeter Pan (1904)Created byJ. M. BarriePortrayed byGerald du Maurier (1904 first stage production)In-universe informationTitleCaptainOccupationPirateNationalityEnglish Captain James Hook is the main antagonist of J. M. Barrie's 1904 play Peter Pan; or, the Boy Who Wouldn't Grow Up and its various adaptations, in ...

 

70 km/h (written incorrectly as kmph) speed limit for light vehicles outside built-up areas. Vehicle categories are motor cars, dual purpose vehicles and motor cycles Road signs in Sri Lanka are standardized to closely follow those used in Europe with certain distinctions, and a number of changes have introduced road signs that suit as per local road and system. Sri Lankan government announced by a gazette that aimed to get a facelift and introduction of over 100 new road traffic signs. The n...

 

East Slavic ethnic group Not to be confused with Ukrani. For other uses, see Ukrainians (disambiguation). This article may require copy editing for grammar. You can assist by editing it. (February 2024) (Learn how and when to remove this template message) UkrainiansУкраїнціTotal populationc. 46 million[1][2][3] Regions with significant populationsUkraine 37,541,700 (2001)[4]Russia1,864,000 (2023)Poland1,651,918 (2023)[5]Canada1,359,655 (2016) ...

Vocal group consisting of young males For other uses, see Boy band (disambiguation). 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: Boy band – news · newspapers · books · scholar · JSTOR (April 2022) (Learn how and when to remove this message) A boy band is loosely defined as a vocal group consisting of you...

 

Qri

QriQri in 2017Nama asal이지현LahirLee Ji-hyun12 Desember 1986 (umur 37)Goyang, South KoreaNama lainQriPekerjaanSingeractressKarier musikGenre K-pop R&B Electropop InstrumenVocalsBassTahun aktif2009–sekarangLabelMBK EntertainmentArtis terkait T-ara QBS Korean nameHangul큐리 Alih AksaraKyuriMcCune–ReischauerK'yuriNama lahirHangul이지현 Hanja李智賢 Alih AksaraI Ji-hyeonMcCune–ReischauerYi Chi-hyŏn Lee Ji Hyun (bahasa Korea: 이지현; Lahir 12 Desember, ...

 

ХристианствоБиблия Ветхий Завет Новый Завет Евангелие Десять заповедей Нагорная проповедь Апокрифы Бог, Троица Бог Отец Иисус Христос Святой Дух История христианства Апостолы Хронология христианства Раннее христианство Гностическое христианство Вселенские соборы Н...

Elezioni generali nel Regno Unito del 2010 Stato  Regno Unito Data 6 maggio Assemblea Camera dei comuni Affluenza 65,1% ( 3,7%) Leader David Cameron Gordon Brown Nick Clegg Liste Conservatori Laburisti Liberal Democratici Voti 10.706.64736,1% 8.604.35829,0% 6.827.93823,0% Seggi 306 / 650 258 / 650 57 / 650 Differenza % 3,7% 6,2% 1.0% Differenza seggi 108 97 5 Distribuzione del voto per collegio Primo ministro David Cameron (Governo Cameron I) 2005 2015 Le elezioni generali nel Regn...

 

Questa voce sull'argomento stagioni delle società calcistiche italiane è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Segui i suggerimenti del progetto di riferimento. Voce principale: Associazione Sportiva Dilettantistica Forlimpopoli 1928. Unione Sportiva ForlimpopoliStagione 1939-1940Sport calcio Squadra Forlimpopoli Allenatore Aldo Neri Presidente Leonello Monterastelli Serie C15º posto nel girone E 1938-1939 1940-1941 Si invita a seguire ...

 

Bufferالشعارمعلومات عامةالمنصة Android, iOS, webمتوفر بلغات Englishموقع الويب buffer.comمعلومات تقنيةالحجم 13.5 MBحالة التطوير Activeالإصدار الأول 30 نوفمبر 2010؛ منذ 13 سنة (2010-11-30)الإصدار الأخير 4.1.2تعديل - تعديل مصدري - تعديل ويكي بيانات بافر (بالإنجليزية: Buffer)، مجموعة من التطبيقات لإدارة ...

Si ce bandeau n'est plus pertinent, retirez-le. Cliquez ici pour en savoir plus. Cette section ou cet article est une traduction incomplète (mai 2011). Vous pouvez modifier la page pour effectuer la traduction. Poncke PrincenPoncke PrincenBiographieNaissance 21 novembre 1925La HayeDécès 22 février 2002 (à 76 ans)JakartaNationalité néerlandaiseActivités Militant pour les droits de la personne humaine, résistant, avocat, homme politiqueAutres informationsLieu de détention Camp de...

 

Location of the state of Kansas in the United States of America The following is a list of symbols of the U.S. state of Kansas.[1] State symbols The flag of the state of Kansas Type Symbol Year and references Kansas state seal Great Seal of the State of Kansas 1861[2] Kansas state flower and floral emblem Wild native sunflower (Helianthus) 1903[3][4] Kansas state banner Kansas state banner 1925[5][6] Kansas state flag Flag of the State of Kansa...

 

東邦大学医療センター大森病院 情報英語名称 Toho University Omori Medical Center前身 東邦大学医学部附属大森病院標榜診療科 内科、心療内科、精神科、神経科、呼吸器科、消化器科、循環器科、リウマチ科、小児科、外科、整形外科、形成外科、脳神経外科、呼吸器外科、心臓血管外科、小児外科、皮膚科、泌尿器科、産科、婦人科、眼科、耳鼻咽喉科、リハビリテーション...

Letk Provinsi Finlandia Barat di Finlandia Finlandia Barat adalah sebuah provinsi Finlandia yang memiliki luas wilayah 74.185 km² dan populasi 1.839.581 jiwa (2002). Ibu kotanya ialah Turku. Kota lainnya di Finlandia Barat Oripää lbsProvinsi di Finlandia Åland · Finlandia Selatan · Finlandia Barat · Finlandia Timur · Laplandia · Oulu lbsKawasan di Finlandia LaplandiaLaplandia OuluKainuu · Ostrobothnia Utara Finlandia B...

 

1996 compilation album by Sex PistolsSpunk/This is CrapCompilation album by Sex PistolsReleased1996Recorded1976–1977GenrePunk rockSpunk/This is Crap is a rarities album by the English punk rock band The Sex Pistols. It was included with the 1996 reissue of Never Mind the Bollocks, Here's the Sex Pistols. It features a reissue of the Spunk bootleg, without talking between tracks and with nine additional tracks.[1] Track listing Seventeen Satellite No Feelings I Wanna Be Me S...

 

Soviet Ukrainian politician (1919–1990) You can help expand this article with text translated from the corresponding article in Russian. (May 2019) Click [show] for important translation instructions. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pasting machine-translated text into the English Wikipedia. Do not transl...

2017 documentary film directed by Alexey Navalny You can help expand this article with text translated from the corresponding article in Russian. (March 2017) Click [show] for important translation instructions. View a machine-translated version of the Russian article. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pastin...

 

Airline of the former Dutch East Indies This article includes a list of general references, but it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (January 2013) (Learn how and when to remove this message) Koninklijke Nederlandsch-Indische Luchtvaart MaatschappijFounded16 July 1928Commenced operations1 November 1928Ceased operations1 August 1947HubsTjililitan AirportFocus citiesBandoeng, Semarang, Medan, Soerabaja, Pa...