2
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
3
/* This Source Code Form is subject to the terms of the Mozilla Public
4
* License, v. 2.0. If a copy of the MPL was not distributed with this
5
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7
//-----------------------------------------------------------------------
9
var summary = "Lamport Bakery's algorithm for mutual exclusion";
10
// Adapted from pseudocode in Wikipedia:
11
// http://en.wikipedia.org/wiki/Lamport%27s_bakery_algorithm
15
var N = 15; // Number of threads.
16
var LOOP_COUNT = 10; // Number of times each thread should loop
19
for (let i = 0; i < n; i++)
24
let x = Number.NEGATIVE_INFINITY;
31
// the mutex mechanism
32
var entering = [false for (i in range(N))];
33
var ticket = [0 for (i in range(N))];
35
// the object being protected
41
ticket[i] = 1 + max(ticket);
44
for (let j = 0; j < N; j++) {
45
// If thread j is in the middle of getting a ticket, wait for that to
50
// Wait until all threads with smaller ticket numbers or with the same
51
// ticket number, but with higher priority, finish their work.
52
while ((ticket[j] != 0) && ((ticket[j] < ticket[i]) ||
53
((ticket[j] == ticket[i]) && (i < j))))
63
for (let k = 0; k < LOOP_COUNT; k++) {
66
// The critical section
76
function makeWorker(id) {
77
return function () { return worker(id); };
83
if (typeof scatter == 'undefined' || typeof sleep == 'undefined') {
84
print('Test skipped. scatter or sleep not defined.');
85
expect = actual = 'Test skipped.';
87
scatter([makeWorker(i) for (i in range(N))]);
89
expect = "counter: " + (N * LOOP_COUNT);
90
actual = "counter: " + counter;
93
reportCompare(expect, actual, summary);