Debian Codegraph @

rhino/testsrc/tests/js1_8/extensions/dekker.js

raw symbols SCIP
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6 var gTestfile = 'dekker.js';
7 //-----------------------------------------------------------------------------
8
9 var summary = "Dekker's algorithm for mutual exclusion";
10 // Adapted from pseudocode in Wikipedia:
11 // http://en.wikipedia.org/wiki/Dekker%27s_algorithm
12
13 printStatus (summary);
14
15 var N = 500; // number of iterations
16
17 // the mutex mechanism
18 var f = [false, false];
19 var turn = 0;
20
21 // resource being protected
22 var counter = 0;
23
24 function worker(me) {
25 let him = 1 - me;
26
27 for (let i = 0; i < N; i++) {
28 // enter the mutex
29 f[me] = true;
30 while (f[him]) {
31 if (turn != me) {
32 f[me] = false;
33 while (turn != me)
34 ; // busy wait
35 f[me] = true;
36 }
37 }
38
39 // critical section
40 let x = counter;
41 sleep(0.003);
42 counter = x + 1;
43
44 // leave the mutex
45 turn = him;
46 f[me] = false;
47 }
48
49 return 'ok';
50 }
51
52 var expect;
53 var actual;
54
55 if (typeof scatter == 'undefined' || typeof sleep == 'undefined') {
56 print('Test skipped. scatter or sleep not defined.');
57 expect = actual = 'Test skipped.';
58 } else {
59 var results = scatter([function () { return worker(0); },
60 function () { return worker(1); }]);
61
62 expect = "Thread status: [ok,ok], counter: " + (2 * N);
63 actual = "Thread status: [" + results + "], counter: " + counter;
64 }
65
66 reportCompare(expect, actual, summary);