| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
var gTestfile = 'peterson.js'; |
| 7 |
|
| 8 |
|
| 9 |
var summary = "Peterson's algorithm for mutual exclusion"; |
| 10 |
|
| 11 |
printStatus(summary); |
| 12 |
|
| 13 |
var N = 500; |
| 14 |
|
| 15 |
|
| 16 |
var f = [false, false]; |
| 17 |
var turn = 0; |
| 18 |
|
| 19 |
|
| 20 |
var counter = 0; |
| 21 |
|
| 22 |
function worker(me) { |
| 23 |
let him = 1 - me; |
| 24 |
|
| 25 |
for (let i = 0; i < N; i++) { |
| 26 |
|
| 27 |
f[me] = true; |
| 28 |
turn = him; |
| 29 |
while (f[him] && turn == him) |
| 30 |
; |
| 31 |
|
| 32 |
|
| 33 |
let x = counter; |
| 34 |
sleep(0.003); |
| 35 |
counter = x+1; |
| 36 |
|
| 37 |
|
| 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); |