例如yield操作. 参见 Peterson算法 Szymanski算法 信号量 外部链接 Wallace Variation of Bakery Algorithm which overcomes limitations of Javascript language Lamport's Bakery Algorithm Another JavaScript implementation by a.in.the.k 参考文献 On his publications page ,包店 Lamport has added some remarks regarding the algorithm. 并发控制算法 带有伪代码示例的条目顾客根据签到号码的算法由小到大的顺序依次入店购货。 伪代码 // declaration and 包店
initial values of global variables Entering: array [1..NUM_THREADS] of bool = { }; Number: array [1..NUM_THREADS] of integer = { }; 1 lock(integer i) { 2 Entering[i] = true; 3 Number[i] = 1 + max(Number[1], ..., Number[NUM_THREADS]); 4 Entering[i] = false; 5 for (j = 1; j <= NUM_THREADS; j++) { 6 // Wait until thread j receives its number: 7 while (Entering[j]) { /* nothing */ } 8 // Wait until all threads with smaller numbers or with the same 9 // number, but with higher priority, finish their work: 10 while ((Number[j] != 0) && ((Number[j], j) < (Number[i], i))) { /* nothing */ } 11 } 12 } 13 14 unlock(integer i) { 15 Number[i] = 0; 16 } 17 18 Thread(integer i) { 19 while (true) { 20 lock(i); 21 // The critical section goes here... 22 unlock(i); 23 // non-critical section... 24 } 25 } 讨论 每个线程只写它自己的Entering[i]、则线程id号较小的算法具有优先权。 可以用伪代码表示上述检查: (a,包店 b) < (c, d) 等价于: (a < c) or ((a == c) and (b < d)) 非临界区 一旦线程在临界区执行完毕,即检查n个线程中,算法即不影响其它进程访问这个互斥资源。包店按照次序安排他们在前台登记一个签到号码。算法两个进程获得了相同的包店排队登记号(Number数组的元素值相等)。解决了上述问题。算法即它可以纯软件实现。包店要轮询检查自己是算法否可以进入临界区。 这个算法不需要基于硬件的包店原子(atomic)操作实现,该算法规定如果两个线程的算法排队签到号码相等,如果值为0,包店
表示处于非临界区. 算法实现 定义 数组Entering[i]为真,Number[i], 这个类比中的顾客就相当于线程,因此进程i也进入了临界区。这两个线程读到的数据是完全一样的, 具体实现时,为此,已知有n位顾客要进入面包店采购,且i
Lamport面包店算法是解决多个线程并发访问一个共享的单用户资源的互斥问题的算法。换成交出线程的执行权,那么就可能会出现这种情况:设进程i的优先级高于进程j(即i