纳呆什么意思| 日本是什么时候投降的| 身上起火疖子什么原因| 农历六月十九是什么日子| 阁楼是什么意思| 看日出是什么生肖| 与其让你在我怀中枯萎是什么歌| 光滑念珠菌是什么意思| 吹空调嗓子疼吃什么药| 一蹴而就什么意思| 黄鼠狼为什么怕鹅| 滴虫性阴炎用什么药效果最好| cps什么意思| 鳕鱼是什么鱼| 狮子座什么星象| 穿拖鞋脚臭是什么原因| 脾胃虚弱吃什么药调理| 北京的简称是什么| 女人梦见血是什么预兆| 福星贵人是什么意思| 梦到绿色的蛇是什么意思| 皮肤瘙痒症用什么药| 芭蕉和香蕉有什么区别| 妈妈的舅舅叫什么| 挛缩是什么意思| 盆腔积液吃什么药好| 特斯拉是什么电池| a2是什么意思| zara是什么牌子| 自言自语是什么原因导致| 牛大力和什么泡酒壮阳| 一般细菌涂片检查是查什么| 小米手机最新款是什么型号| 杀跌是什么意思| 血压高看什么科| 乙肝病毒表面抗体高是什么意思| 挑担是什么关系| 香米是什么米| 看结石挂什么科室| 九零年属什么生肖| 周杰伦有什么病| pt950是什么材质| dwi呈高信号什么意思| 桂花是什么生肖| 阿玛尼是什么意思| 9月16日是什么星座| as是什么| 怀疑是什么意思| 对什么都不感兴趣| 铁观音适合什么季节喝| 放河灯是什么节日| 硝苯地平是什么药| 优甲乐是治什么病的| 舌头干涩是什么原因| 美乃滋是什么| 开黄腔什么意思| 梦见骆驼是什么意思| 拔完牙后能吃什么| 什么手机像素好| 眼睛发痒是什么原因| 面色潮红是什么原因| 钢琴8级什么水平| 小分子水是什么水| 群什么吐什么| 胳膊肘往外拐是什么意思| 最高学历是什么| 躺尸是什么意思| 黄子韬爸爸是干什么的| maby什么意思| 狐假虎威告诉我们什么道理| 焖子是什么做的| 指甲表面凹凸不平是什么原因| 宝宝喝什么奶粉好| 紫菜和海苔有什么区别| 狗狗不能吃什么水果| 你从什么时候不再爱我| 扫地僧是什么意思| 办身份证需要什么| 困是什么原因| 二加一笔是什么字| 63岁属什么| 小孩老咳嗽是什么原因| u型压迹是什么意思| 宝宝流鼻涕吃什么药| 天狗是什么意思| 痔疮什么样子| 主动脉夹层什么意思| 商纣王叫什么名字| 肚脐上方是什么器官| 什么是人生格言| 7月8号是什么日子| 音准是什么意思| 一进大门看见什么最好| 脾脏结节一般是什么病| 什么生日的人有佛缘| 感冒吃什么水果比较好| 检查全身挂什么科| 谷雨是什么时候| 犯困是什么原因| 猫咪黑下巴是什么原因| 男人秒射是什么原因| 全科医学科看什么病| 空气是由什么组成的| 孤寡老人国家有什么政策| 上善若水什么意思| 吃莲子有什么好处| 吃海鲜不能吃什么水果| 化疗病人吃什么好| 什么意思啊| 娇妻是什么意思| 推拿是什么意思| 呼吸内镜检查什么| 槿字五行属什么| 男性雄激素低吃什么药| 看指甲去医院挂什么科| 天蝎座和什么星座最配| 蚊子会传播什么疾病| 养老院和敬老院有什么区别| friend什么意思中文| 肚子痛拉肚子吃什么药| 手术后吃什么营养品好| 虾仁不能和什么食物一起吃| 吃什么食物可以去湿气| 生吃胡萝卜有什么好处和坏处| 玫瑰什么时候开花| 情绪高涨是什么意思| 知了吃什么| 乳香是什么东西| 富氢水是什么| 泳字五行属什么| 贴水是什么意思| 直肠壁增厚一般是什么情况| 儿童头痛挂什么科| 95年属什么生肖婚配表| 995是什么意思| 肝内胆管结石有什么症状表现| 腹主动脉壁钙化是什么意思| 生姜什么时候种| 750是什么金| 脂溶性是什么意思| 咳嗽吐白痰吃什么药| 植物油是什么| 土是念什么| 抖s什么意思| 紫罗兰色是什么颜色| 张飞穿针歇后语下一句是什么| usc是什么意思| 蒲公英叶和根的功效有什么不同| est.是什么意思| sob是什么意思| 巧囊是什么原因形成的| 阴道里面痒用什么药| 脚脖子粗是什么原因| 阔腿裤配什么鞋子好看| 喊麦是什么意思| 俄罗斯人是什么人种| 睾丸扭转是什么意思| 三点水翟读什么| 睡觉起来头晕什么原因| 骨赘形成是什么意思| 罗汉果泡水有什么好处| 7.11是什么日子| 什么叫直男| 复古红是什么颜色| 一月来两次月经是什么原因| 一个目一个于念什么| 嫡庶是什么意思| 果酸是什么东西| 凹陷性疤痕用什么药膏| 党内的最高处分是什么| 握手是什么意思| 倒班什么意思| 离家出走需要准备什么| 膈应是什么意思| 高密度脂蛋白是什么| 幼小衔接都学什么知识| 月经血量少是什么原因| 七夕送什么礼物好| 飞机杯是什么意思| 隔桌不买单是什么意思| 子夜是指什么时间| 什么花走着开| 小太阳是什么意思| 走路快的人是什么性格| 数字化摄影dr是检查什么| 天蝎是什么动物| 过度纵欲的后果是什么| 秀才指什么生肖| 无以言表是什么意思| 血小板压积偏高是什么意思| 膈应人是什么意思| 双子座爱吃什么| 香港的海是什么海| 吹空调头疼是什么原因| 黄花菜不能和什么一起吃| 做爱时间短吃什么药好| 吥是什么意思| rich什么意思| 生长激素分泌的高峰期是什么时候| 珑字五行属什么| 一什么桃花| 数字五行属什么| 菠萝蜜不能和什么一起吃| 长明灯是什么意思| 手心脚心热是什么原因| 癣用什么药膏| 折耳根什么味道| 入木三分是什么生肖| 什能组什么词| 脑垂体在什么位置图片| 盆底肌松弛有什么症状| 消融是什么意思| vod是什么意思| 疔是什么意思| 阳虚吃什么药| 须尽欢什么意思| 尊敬是什么意思| 什么是抑郁| 肩膀疼吃什么药| 拉格啤酒是什么意思| 瘦西湖为什么叫瘦西湖| 农历11月11日是什么星座| 煮玉米放盐起什么作用| 四川为什么叫四川| ader是什么牌子| 玻璃体混浊吃什么药好| 婴儿什么时候会走路| notebook是什么意思| 爱上一个人是什么感觉| 工作单位是什么| 熳是什么意思| 周传雄得了什么病| 经常呕吐是什么原因| 上校是什么级别| 做梦梦见火是什么征兆| 不完全骨折是什么意思| 1994属什么生肖| 6月适合种什么菜| 九月初三是什么星座| nsnm什么意思| 性病有什么症状| 二十年是什么婚| 咳嗽是什么原因| 晴对什么| 头晕是什么感觉| 什么是邪淫| 尿里有泡沫是什么原因| 反流性食管炎可以吃什么水果| 人丹是什么药| 黄芪和什么搭配最好| 嘴唇上长痣代表什么| 眼线是什么意思| 股票里xd是什么意思| 什么刻| 土豆什么时候收获| 明胶是什么做的| 什么水果是降火的| 鹅喜欢吃什么草| 肺栓塞的主要症状是什么| 5.19是什么星座| 白细胞酯酶弱阳性什么意思| 994是什么意思| 朱元璋为什么杀李善长| 618是什么意思| 百度Jump to content

宁德市医院开展“关爱健康 你问我答”金秋义诊

From Wikipedia, the free encyclopedia
(Redirected from Lamport's Bakery algorithm)
百度   “奉法者强则国强,奉法者弱则国弱。

Lamport's bakery algorithm is a computer algorithm devised by computer scientist Leslie Lamport, as part of his long study of the formal correctness of concurrent systems, which is intended to improve the safety in the usage of shared resources among multiple threads by means of mutual exclusion.

In computer science, it is common for multiple threads to simultaneously access the same resources. Data corruption can occur if two or more threads try to write into the same memory location, or if one thread reads a memory location before another has finished writing into it. Lamport's bakery algorithm is one of many mutual exclusion algorithms designed to prevent concurrent threads entering critical sections of code concurrently to eliminate the risk of data corruption.

Algorithm

[edit]

Analogy

[edit]

Lamport envisioned a bakery with a numbering machine at its entrance so each customer is given a unique number. Numbers increase by one as customers enter the store. A global counter displays the number of the customer that is currently being served. All other customers must wait in a queue until the baker finishes serving the current customer and the next number is displayed. When the customer is done shopping and has disposed of their number, the clerk increments the number, allowing the next customer to be served. That customer must draw another number from the numbering machine in order to shop again.

According to the analogy, the "customers" are threads, identified by the letter i, obtained from a global variable.

Due to the limitations of computer architecture, some parts of Lamport's analogy need slight modification. It is possible that more than one thread will get the same number n when they request it; this cannot be avoided (without first solving the mutual exclusion problem, which is the goal of the algorithm). Therefore, it is assumed that the thread identifier i is also a priority. A lower value of i means a higher priority and threads with higher priority will enter the critical section first.

Critical section

[edit]

The critical section is that part of code that requires exclusive access to resources and may only be executed by one thread at a time. In the bakery analogy, it is when the customer trades with the baker that others must wait.

When a thread wants to enter the critical section, it has to check whether now is its turn to do so. It should check the number n of every other thread to make sure that it has the smallest one. In case another thread has the same number, the thread with the smallest i will enter the critical section first.

In pseudocode this comparison between threads a and b can be written in the form:

// Let na - the customer number for thread a, and
// ia - the thread number for thread a, then

(na, ia) < (nb, ib) 

which is equivalent to:

(na < nb) or ((na == nb) and (ia < ib))

Once the thread ends its critical job, it gets rid of its number and enters the non-critical section.

Non-critical section

[edit]

The non-critical section is the part of code that doesn't need exclusive access. It represents some thread-specific computation that doesn't interfere with other threads' resources and execution.

This part is analogous to actions that occur after shopping, such as putting change back into the wallet.

Implementation of the algorithm

[edit]

Definitions

[edit]

In Lamport's original paper, the entering variable is known as choosing, and the following conditions apply:

  • Words choosing [i] and number [i] are in the memory of process i, and are initially zero.
  • The range of values of number [i] is unbounded.
  • A process may fail at any time. We assume that when it fails, it immediately goes to its noncritical section and halts. There may then be a period when reading from its memory gives arbitrary values. Eventually, any read from its memory must give a value of zero.

Code examples

[edit]

Pseudocode

[edit]

In this example, all threads execute the same "main" function, Thread. In real applications, different threads often have different "main" functions.

Note that as in the original paper, the thread checks itself before entering the critical section. Since the loop conditions will evaluate as false, this does not cause much delay.

  // declaration and initial values of global variables
  Entering: array [1..NUM_THREADS] of bool = {false};
  Number: array [1..NUM_THREADS] of integer = {0};

  lock(integer i) {
      Entering[i] = true;
      Number[i] = 1 + max(Number[1], ..., Number[NUM_THREADS]);
      Entering[i] = false;
      for (integer j = 1; j <= NUM_THREADS; j++) {
          // Wait until thread j receives its number:
          while (Entering[j]) { /* nothing */ }
          // Wait until all threads with smaller numbers or with the same
          // number, but with higher priority, finish their work:
          while ((Number[j] != 0) && ((Number[j], j) < (Number[i], i))) { /* nothing */ }
      }
  }
  
  unlock(integer i) {
      Number[i] = 0;
  }

  Thread(integer i) {
      while (true) {
          lock(i);
          // The critical section goes here...
          unlock(i);
          // non-critical section...
      }
  }

Each thread only writes its own storage, only reads are shared. It is remarkable that this algorithm is not built on top of some lower level "atomic" operation, e.g. compare-and-swap. The original proof shows that for overlapping reads and writes to the same storage cell only the write must be correct.[clarification needed] The read operation can return an arbitrary number. Therefore, this algorithm can be used to implement mutual exclusion on memory that lacks synchronisation primitives, e.g., a simple SCSI disk shared between two computers.

The necessity of the variable Entering might not be obvious as there is no 'lock' around lines 7 to 13. However, suppose the variable was removed and two processes computed the same Number[i]. If the higher-priority process was preempted before setting Number[i], the low-priority process will see that the other process has a number of zero, and enters the critical section; later, the high-priority process will ignore equal Number[i] for lower-priority processes, and also enters the critical section. As a result, two processes can enter the critical section at the same time. The bakery algorithm uses the Entering variable to make the assignment on line 6 look like it was atomic; process i will never see a number equal to zero for a process j that is going to pick the same number as i.

When implementing the pseudo code in a single process system or under cooperative multitasking, it is better to replace the "do nothing" sections with code that notifies the operating system to immediately switch to the next thread. This primitive is often referred to as yield.

Lamport's bakery algorithm assumes a sequential consistency memory model. Few, if any, languages or multi-core processors implement such a memory model. Therefore, correct implementation of the algorithm typically requires inserting fences to inhibit reordering.[1]

We declare N to be the number of processes, and we assume that N is a natural number.

CONSTANT N
ASSUME N \in Nat

We define P to be the set {1, 2, ... , N} of processes.

P == 1..N

The variables num and flag are declared as global.

--algorithm AtomicBakery {
variable num = [i \in P |-> 0], flag = [i \in P |-> FALSE];

The following defines LL(j, i) to be true iff <<num[j], j>> is less than or equal to <<num[i], i>> in the usual lexicographical ordering.

define { LL(j, i) == \/ num[j] < num[i]
                     \/ /\ num[i] = num[j]
                        /\ j =< i
       }

For each element in P there is a process with local variables unread, max and nxt. Steps between consecutive labels p1, ..., p7, cs are considered atomic. The statement with (x \in S) { body } sets id to a nondeterministically chosen element of the set S and then executes body. A step containing the statement await expr can be executed only when the value of expr is TRUE.

process (p \in P)
  variables unread \in SUBSET P, 
            max \in Nat, 
            nxt \in P;
{
p1: while (TRUE) {
      unread := P \ {self} ;
      max := 0;
      flag[self] := TRUE;
p2:   while (unread # {}) {
        with (i \in unread) { unread := unread \ {i};
                              if (num[i] > max) { max := num[i]; }
         }
       };
p3:   num[self] := max + 1;
p4:   flag[self] := FALSE;
      unread := P \ {self} ;
p5:   while (unread # {}) {
        with (i \in unread) { nxt := i ; };
        await ~ flag[nxt];
p6:     await \/ num[nxt] = 0
              \/ LL(self, nxt) ;
        unread := unread \ {nxt};
        } ;
cs:   skip ;  \* the critical section;
p7:   num[self] := 0;
 }}
}

Java code

[edit]

We use the AtomicIntegerArray class not for its built in atomic operations but because its get and set methods work like volatile reads and writes. Under the Java Memory Model this ensures that writes are immediately visible to all threads.

AtomicIntegerArray ticket = new AtomicIntegerArray(threads); // ticket for threads in line, n - number of threads
// Java initializes each element of 'ticket' to 0
 
AtomicIntegerArray entering = new AtomicIntegerArray(threads); // 1 when thread entering in line
// Java initializes each element of 'entering' to 0
 
public void lock(int pid) // thread ID
{
    entering.set(pid, 1);
    int max = 0;
    for (int i = 0; i < threads; i++)
    {
        int current = ticket.get(i);
        if (current > max)
        {
            max = current;
        }
    }
    ticket.set(pid, 1 + max); 
    entering.set(pid, 0);
    for (int i = 0; i < ticket.length(); ++i)
    {
        if (i != pid)
        {
            while (entering.get(i) == 1) { Thread.yield(); } // wait while other thread picks a ticket
            while (ticket.get(i) != 0 && ( ticket.get(i) < ticket.get(pid) ||
                    (ticket.get(i) == ticket.get(pid) && i < pid)))
            { Thread.yield(); }
        }
    }
    // The critical section goes here...
}

public void unlock(int pid)
{
    ticket.set(pid, 0);
}

See also

[edit]

References

[edit]
  1. ^ Chinmay Narayan, Shibashis Guha, S.Arun-Kumar Inferring Fences in a Concurrent Program Using SC proof of Correctness
[edit]
小腹痛挂什么科 为什么会得骨癌 眼镜框什么材质的好 什么算熬夜 ns是什么意思
老炮儿是什么意思啊 什么叫知己 91是什么 长颈鹿代表什么生肖 三点水的字和什么有关
潮汕立冬吃什么 脑梗吃什么药效果最好 牛河是什么 611是什么意思 肺结节什么东西不能吃
后羿射日是什么意思 烤冷面是什么做的 什么水什么什么 补充胶原蛋白吃什么最好 食指戴戒指代表什么
kawasaki是什么牌子wuhaiwuya.com 家里养什么花最好hcv7jop5ns3r.cn 淋球菌阳性是什么意思hcv8jop1ns6r.cn ms.是什么意思hcv8jop6ns7r.cn 什么软件可以开空调hcv7jop4ns7r.cn
身高别体重是什么意思hcv8jop1ns7r.cn 什么是塔罗牌hcv7jop9ns4r.cn 手指甲没有月牙是什么原因hcv7jop4ns8r.cn 莲子有什么功效hcv7jop6ns6r.cn 喝什么去火hcv8jop1ns2r.cn
世界上最贵的狗是什么zsyouku.com 11.23是什么星座hcv8jop2ns0r.cn 整形什么医院好hcv9jop2ns2r.cn 楚乔传2什么时候上映hcv9jop2ns1r.cn 怀孕肚子痒是什么原因bysq.com
开心果树长什么样hcv8jop7ns9r.cn 血肌酐高是什么原因hcv9jop1ns5r.cn 宫颈纳囊多发是什么意思inbungee.com 心情沉重是什么意思hcv8jop3ns9r.cn 野生天麻长什么样图片gysmod.com
百度