js/src/tests/js1_8/extensions/peterson.js

branch
TOR_BUG_9701
changeset 14
925c144e1f1f
equal deleted inserted replaced
-1:000000000000 0:306d3756d927
1 // |reftest| skip
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/. */
6
7 //-----------------------------------------------------------------------
8
9 var summary = "Peterson's algorithm for mutual exclusion";
10
11 printStatus(summary);
12
13 var N = 500; // number of iterations
14
15 // the mutex mechanism
16 var f = [false, false];
17 var turn = 0;
18
19 // the resource being protected
20 var counter = 0;
21
22 function worker(me) {
23 let him = 1 - me;
24
25 for (let i = 0; i < N; i++) {
26 // enter the mutex
27 f[me] = true;
28 turn = him;
29 while (f[him] && turn == him)
30 ; // busy wait
31
32 // critical section
33 let x = counter;
34 sleep(0.003);
35 counter = x+1;
36
37 // leave the mutex
38 f[me] = false;
39 }
40
41 return 'ok';
42 }
43
44 var expect;
45 var actual;
46
47 if (typeof scatter == 'undefined' || typeof sleep == 'undefined') {
48 print('Test skipped. scatter or sleep not defined.');
49 expect = actual = 'Test skipped.';
50 } else {
51 var results = scatter ([function() { return worker(0); },
52 function() { return worker(1); }]);
53 expect = "Thread status: [ok,ok], counter: " + (2 * N);
54 actual = "Thread status: [" + results + "], counter: " + counter;
55 }
56
57 reportCompare(expect, actual, summary);

mercurial