1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/js/src/tests/js1_8/extensions/peterson.js Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,57 @@ 1.4 +// |reftest| skip 1.5 +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 1.6 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.7 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.8 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.9 + 1.10 +//----------------------------------------------------------------------- 1.11 + 1.12 +var summary = "Peterson's algorithm for mutual exclusion"; 1.13 + 1.14 +printStatus(summary); 1.15 + 1.16 +var N = 500; // number of iterations 1.17 + 1.18 +// the mutex mechanism 1.19 +var f = [false, false]; 1.20 +var turn = 0; 1.21 + 1.22 +// the resource being protected 1.23 +var counter = 0; 1.24 + 1.25 +function worker(me) { 1.26 + let him = 1 - me; 1.27 + 1.28 + for (let i = 0; i < N; i++) { 1.29 + // enter the mutex 1.30 + f[me] = true; 1.31 + turn = him; 1.32 + while (f[him] && turn == him) 1.33 + ; // busy wait 1.34 + 1.35 + // critical section 1.36 + let x = counter; 1.37 + sleep(0.003); 1.38 + counter = x+1; 1.39 + 1.40 + // leave the mutex 1.41 + f[me] = false; 1.42 + } 1.43 + 1.44 + return 'ok'; 1.45 +} 1.46 + 1.47 +var expect; 1.48 +var actual; 1.49 + 1.50 +if (typeof scatter == 'undefined' || typeof sleep == 'undefined') { 1.51 + print('Test skipped. scatter or sleep not defined.'); 1.52 + expect = actual = 'Test skipped.'; 1.53 +} else { 1.54 + var results = scatter ([function() { return worker(0); }, 1.55 + function() { return worker(1); }]); 1.56 + expect = "Thread status: [ok,ok], counter: " + (2 * N); 1.57 + actual = "Thread status: [" + results + "], counter: " + counter; 1.58 +} 1.59 + 1.60 +reportCompare(expect, actual, summary);