Peterson's algorithm

Peterson's algorithm (or Peterson's solution) is a concurrent programming algorithm for mutual exclusion that allows two or more processes to share a single-use resource without conflict, using only shared memory for communication. It was formulated by Gary L. Peterson in 1981.[1] While Peterson's original formulation worked with only two processes, the algorithm can be generalized for more than two.[2]

The algorithm

The algorithm uses two variables: flag and turn. A flag[n] value of true indicates that the process n wants to enter the critical section. Entrance to the critical section is granted for process P0 if P1 does not want to enter its critical section or if P1 has given priority to P0 by setting turn to 0.

Peterson's algorithm
bool flag[2] = {false, false};
int turn;
P0:      flag[0] = true;
P0_gate: turn = 1;
         while (flag[1] && turn == 1)
         {
             // busy wait
         }
         // critical section
         ...
         // end of critical section
         flag[0] = false;
P1:      flag[1] = true;
P1_gate: turn = 0;
         while (flag[0] && turn == 0)
         {
             // busy wait
         }
         // critical section
         ...
         // end of critical section
         flag[1] = false;

The algorithm satisfies the three essential criteria to solve the critical-section problem. The while condition works even with preemption.[1]

The three criteria are mutual exclusion, progress, and bounded waiting.[3]

Since turn can take on one of two values, it can be replaced by a single bit, meaning that the algorithm requires only three bits of memory.[4]: 22 

Mutual exclusion

P0 and P1 can never be in the critical section at the same time. If P0 is in its critical section, then flag[0] is true. In addition, either flag[1] is false (meaning that P1 has left its critical section), or turn is 0 (meaning that P1 is just now trying to enter the critical section, but graciously waiting), or P1 is at label P1_gate (trying to enter its critical section, after setting flag[1] to true but before setting turn to 0 and busy waiting). So if both processes are in their critical sections, then we conclude that the state must satisfy flag[0] and flag[1] and turn = 0 and turn = 1. No state can satisfy both turn = 0 and turn = 1, so there can be no state where both processes are in their critical sections. (This recounts an argument that is made rigorous in Schneider 1997.[5])

Progress

Progress is defined as the following: if no process is executing in its critical section and some processes wish to enter their critical sections, then only those processes that are not executing in their remainder sections can participate in making the decision as to which process will enter its critical section next. Note that for a process or thread, the remainder sections are parts of the code that are not related to the critical section. This selection cannot be postponed indefinitely.[3] A process cannot immediately re-enter the critical section if the other process has set its flag to say that it would like to enter its critical section.

Bounded waiting

Bounded waiting, or bounded bypass, means that the number of times a process is bypassed by another process after it has indicated its desire to enter the critical section is bounded by a function of the number of processes in the system.[3][4]: 11  In Peterson's algorithm, a process will never wait longer than one turn for entrance to the critical section.

Filter algorithm: Peterson's algorithm for more than two processes

Snapshot of filter algorithm with 10 processes in progress. Last to enter are shown bold and underlined. (NB: Depending on scheduling, the last to enter may not be "correct".) At any time, updates to the table could be: the insertion of a new process at level 0, a change to the last to enter at a given level, or a process moving up one level (if it is not the last to enter OR there are no other processes at its own level or higher).

The filter algorithm generalizes Peterson's algorithm to N > 2 processes.[6] Instead of a boolean flag, it requires an integer variable per process, stored in a single-writer/multiple-reader (SWMR) atomic register, and N − 1 additional variables in similar registers. The registers can be represented in pseudocode as arrays:

level : array of N integers
last_to_enter : array of N − 1 integers

The level variables take on values up to N − 1, each representing a distinct "waiting room" before the critical section.[6] Processes advance from one room to the next, finishing in room N − 1, which is the critical section. Specifically, to acquire a lock, process i executes[4]: 22 

i ← ProcessNo
forfrom 0 to N − 1 exclusive
    level[i] ← ℓ
    last_to_enter[ℓ] ← i
    while last_to_enter[ℓ] = i and there exists k ≠ i, such that level[k] ≥ ℓ
        wait

To release the lock upon exiting the critical section, process i sets level[i] to −1.

That this algorithm achieves mutual exclusion can be proven as follows. Process i exits the inner loop when there is either no process with a higher level than level[i], so the next waiting room is free; or, when i ≠ last_to_enter[ℓ], so another process joined its waiting room. At level zero, then, even if all N processes were to enter waiting room zero at the same time, no more than N − 1 will proceed to the next room, the final one finding itself the last to enter the room. Similarly, at the next level, N − 2 will proceed, etc., until at the final level, only one process is allowed to leave the waiting room and enter the critical section, giving mutual exclusion.[4]: 22–24 

Unlike the two-process Peterson algorithm, the filter algorithm does not guarantee bounded waiting.[4]: 25–26 

Note

When working at the hardware level, Peterson's algorithm is typically not needed to achieve atomic access. Some processors have special instructions, like test-and-set or compare-and-swap, which, by locking the memory bus, can be used to provide mutual exclusion in SMP systems.

Most modern CPUs reorder memory accesses to improve execution efficiency (see memory ordering for types of reordering allowed). Such processors invariably give some way to force ordering in a stream of memory accesses, typically through a memory barrier instruction. Implementation of Peterson's and related algorithms on processors that reorder memory accesses generally requires use of such operations to work correctly to keep sequential operations from happening in an incorrect order. Note that reordering of memory accesses can happen even on processors that don't reorder instructions (such as the PowerPC processor in the Xbox 360).[citation needed]

Most such CPUs also have some sort of guaranteed atomic operation, such as XCHG on x86 processors and load-link/store-conditional on Alpha, MIPS, PowerPC, and other architectures. These instructions are intended to provide a way to build synchronization primitives more efficiently than can be done with pure shared memory approaches.

See also

Footnotes

  1. ^ a b G. L. Peterson: "Myths About the Mutual Exclusion Problem", Information Processing Letters 12(3) 1981, 115–116
  2. ^ As discussed in Operating Systems Review, January 1990 ("Proof of a Mutual Exclusion Algorithm", M Hofri).
  3. ^ a b c Silberschatz. Operating Systems Concepts: Seventh Edition. John Wiley and Sons, 2005, Page 194.
  4. ^ a b c d e Raynal, Michel (2012). Concurrent Programming: Algorithms, Principles, and Foundations. Springer Science & Business Media. ISBN 978-3642320279.
  5. ^ F. B. Schneider, On Concurrent Programming, Springer Verlag, 1997, pages 185–196.
  6. ^ a b Herlihy, Maurice; Shavit, Nir (2012). The Art of Multiprocessor Programming. Elsevier. pp. 28–31. ISBN 9780123977953.

Read other articles:

The Armenian film industry produced over ten feature films in 2014. This article fully lists all non-pornographic films, including short films, that had a release date in that year and which were at least partly made by Armenia. It does not include films first released in previous years that had release dates in 2014. Also included is an overview of the major events in Armenian film, including film festivals and awards ceremonies, as well as lists of those films that have been particularly w...

 

 

Kurva bicorn Dalam geometri, bicorn adalah sebuah kurva kuartik rasional yang didefinisikan dengan persamaan[1] y 2 ( a 2 − x 2 ) = ( x 2 + 2 a y − a 2 ) 2 . {\displaystyle y^{2}(a^{2}-x^{2})=(x^{2}+2ay-a^{2})^{2}.} Kurva ini mempunyai dua taring dalam simetrik mengenai sumbu- y {\displaystyle y} .[2] Kurva bicorn dikenal sebagai kurva topi berbentuk segitiga lantaran mempunyai kemiripannya dengan topi bicorne. Sejarah Pada tahun 1864, James Joseph Sylvester memp...

 

 

Monnaie de Vuk Branković. Vuk Branković (en serbe cyrillique Вук Бранковић), était un seigneur médiéval serbe. Fils de Branko Mladenović, qui était le gouverneur de Ohrid et un des conseillers de Stefan Uroš V dit le faible. Il apparaît dans l'histoire vers 1370, en tant que seigneur du Kosovo de Priština, Vučitrn et Zvečan. Skopje est sous son autorité à partir de 1378. Vuk était le beau-fils du Prince Lazar Hrebeljanović, il avait épousé en 1371 sa fille Mara. ...

Гексод Гексо́д — электронная лампа с шестью электродами: катод, анод и четыре сетки. Разработана Карлом Штеймелем[de] — инженером немецкой компании «Телефункен». Первые наработки инженера относятся к 1932 г.[1][2] Техническое описание Появление в лампе четвертой сет...

 

 

Zwolle Hanseatic city (en)munisipalitas di Belandakota besarcadastral populated place in the Netherlands (en)place with town rights and privileges (en) Zwolle (nl) flag of Zwolle (en) coat of arms of Zwolle (en) dan first coat of arms of Zwolle (en) Tempat Negara berdaulatKerajaan BelandaCountry of the Kingdom of the Netherlands (en)BelandaProvinsi di BelandaOverijssel Ibu kota dariOverijssel NegaraBelanda Pembagian administratifWindesheim (en) Brinkhoek (en) Harculo (en) Wijthmen (en) Brugge...

 

 

Association football club in England Football clubWinslow UnitedFull nameWinslow United Football ClubNickname(s)The PloughmenFounded1891; 133 years ago (1891)GroundElmfields Gate,WinslowCapacity2,000 (100 Seated)ChairmanAndy SetterfieldManagerJordan KingLeagueSpartan South Midlands League Division One2022–23Spartan South Midlands League Division One, 9th of 20WebsiteClub website Home colours Away colours Winslow United Football Club are a football club based in Winslow, Bu...

イスラームにおける結婚(イスラームにおけるけっこん)とは、二者の間で行われる法的な契約である。新郎新婦は自身の自由な意思で結婚に同意する。口頭または紙面での規則に従った拘束的な契約は、イスラームの結婚で不可欠だと考えられており、新郎と新婦の権利と責任の概要を示している[1]。イスラームにおける離婚は様々な形をとることができ、個�...

 

 

Voce principale: Associazione Calcistica Perugia Calcio. AC PerugiaStagione 1982-1983I giocatori biancorossi prima di una partita Sport calcio Squadra Perugia Allenatore Aldo Agroppi Presidente Franco D'Attoma Serie B11º Coppa ItaliaPrimo turno Maggiori presenzeCampionato: Ottoni (37) Miglior marcatoreCampionato: Pagliari (10) StadioRenato Curi 1981-1982 1983-1984 Si invita a seguire il modello di voce Questa voce raccoglie le informazioni riguardanti l'Associazione Calcio Perugia ...

 

 

この項目には、一部のコンピュータや閲覧ソフトで表示できない文字が含まれています(詳細)。 数字の大字(だいじ)は、漢数字の一種。通常用いる単純な字形の漢数字(小字)の代わりに同じ音の別の漢字を用いるものである。 概要 壱万円日本銀行券(「壱」が大字) 弐千円日本銀行券(「弐」が大字) 漢数字には「一」「二」「三」と続く小字と、「壱」「�...

内華達州 美國联邦州State of Nevada 州旗州徽綽號:產銀之州、起戰之州地图中高亮部分为内華達州坐标:35°N-42°N, 114°W-120°W国家 美國建州前內華達领地加入聯邦1864年10月31日(第36个加入联邦)首府卡森城最大城市拉斯维加斯政府 • 州长(英语:List of Governors of {{{Name}}}]]) • 副州长(英语:List of lieutenant governors of {{{Name}}}]])喬·隆巴爾多(R斯塔...

 

 

O'GradyÓ GrádaighArms of O'Grady: Per pale gules and sable, three lions passant guardant in pale per pale argent and orParent houseDál gCais[1]CountryKingdom of ThomondTitles Lord of The Banner Viscount Guillamore The O'Grady family, also styled O'Grady of Kilballyowen, is one of Ireland's noble families and surviving Chiefs of the Name. Their title is The O'Grady in English and Ó Gráda in Irish. Naming conventions Main article: Irish personal naming system Male Daughter Wife (L...

 

 

Village in Ozaukee County, Wisconsin This article is about the village. For the adjacent town, see Saukville (town), Wisconsin. Village in Wisconsin, United StatesSaukville, WisconsinVillageThe Milwaukee River in Saukville, WisconsinLocation of Saukville in Ozaukee County, Wisconsin.Coordinates: 43°24′22″N 87°57′47″W / 43.40611°N 87.96306°W / 43.40611; -87.96306Country United StatesState WisconsinCountyOzaukeeSettledc. 1845Incorporated1915&#...

Canadian ice hockey executive This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Doug Armstrong – news · newspapers · books · scholar · JSTOR (August 2023) (Learn how and when to remove this messag...

 

 

Film genre Hong Kong action cinema is the principal source of the Hong Kong film industry's global fame. Action films from Hong Kong have roots in Chinese and Hong Kong cultures including Chinese opera, storytelling and aesthetic traditions, which Hong Kong filmmakers combined with elements from Hollywood and Japanese cinema along with new action choreography and filmmaking techniques, to create a culturally distinctive form that went on to have wide transcultural appeal. In turn, Hollywood a...

 

 

الدوري التونسي لكرة اليد للرجال الموسم 1971-1972 البلد تونس  المنظم الجامعة التونسية لكرة اليد  النسخة 17 عدد الفرق 12   الفائز الترجي الرياضي التونسي جمعية البريد والبرق والهاتف الرياضية (الثاني) الدوري التونسي لكرة اليد 1970–71  الدوري التونسي لكرة اليد 1972–73  تعديل ...

TMPOAvailable structuresPDBOrtholog search: PDBe RCSB List of PDB id codes1GJJ, 1H9F, 1H9EIdentifiersAliasesTMPO, CMD1T, LAP2, LEMD4, PRO0868, TP, thymopoietinExternal IDsOMIM: 188380; MGI: 106920; HomoloGene: 31144; GeneCards: TMPO; OMA:TMPO - orthologsGene location (Human)Chr.Chromosome 12 (human)[1]Band12q23.1Start98,515,579 bp[1]End98,550,351 bp[1]Gene location (Mouse)Chr.Chromosome 10 (mouse)[2]Band10 C2|10 45.66 cMStart90,983,433 bp[2]End91,0...

 

 

Peta wilayah Komune Monte Santa Maria Tiberina (merah) di Provinsi Perugia (emas), Umbria, Italia. Monte Santa Maria Tiberina komune di Italia Monte Santa Maria Tiberina (it) Tempat Negara berdaulatItaliaDaerah di ItaliaUmbraProvinsi di ItaliaProvinsi Perugia NegaraItalia PendudukTotal1.085  (2023 )GeografiLuas wilayah72,53 km² [convert: unit tak dikenal]Ketinggian688 m Berbatasan denganArezzo Monterchi (en) Città di Castello SejarahSanto pelindungMaria Diangkat ke Surga Informasi...

 

 

Ej att förväxla med Mellila (kommun). Melilla Flagga Stadsvapen Land  Spanien Koordinater 35°18′N 2°57′V / 35.300°N 2.950°V / 35.300; -2.950 Yta 12,3 km² Folkmängd 85 159 (2022)[1] Befolkningstäthet 6 923 invånare/km² Borgmästare Juan José Imbroda (PP) Geonames 6362988 MelillaMelillaMelilla (spanska: [meˈliʎa], arabiska: مليلية [maˈliːlja])) är en spansk exklav vid nordafrikanska Medelhavskusten med la...

Cet article est une ébauche concernant l’eau. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Si ce bandeau n'est plus pertinent, retirez-le. Cliquez ici pour en savoir plus. Cet article ne s'appuie pas, ou pas assez, sur des sources secondaires ou tertiaires (novembre 2020). Pour améliorer la vérifiabilité de l'article ainsi que son intérêt encyclopédique, il est nécessaire, quand des sources primaire...

 

 

Cet article est une ébauche concernant la Chine. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Huáchí Xiàn 华池县 Administration Pays Chine Province ou région autonome Gansu Préfecture Qingyang Statut administratif Xian Code postal 745600[1] Indicatif +86 (0)934 Immatriculation 甘M Démographie 124 299 hab. (1999) Densité 33 hab./km2 Géographie Coordonnées 36° 25′ 00″...