michael@0: // |reftest| skip michael@0: /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* michael@0: * Any copyright is dedicated to the Public Domain. michael@0: * http://creativecommons.org/licenses/publicdomain/ michael@0: * Contributor: Jason Orendorff michael@0: */ michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: michael@0: var summary = "Dekker's algorithm for mutual exclusion"; michael@0: // Adapted from pseudocode in Wikipedia: michael@0: // http://en.wikipedia.org/wiki/Dekker%27s_algorithm michael@0: michael@0: printStatus (summary); michael@0: michael@0: var N = 500; // number of iterations michael@0: michael@0: // the mutex mechanism michael@0: var f = [false, false]; michael@0: var turn = 0; michael@0: michael@0: // resource being protected michael@0: var counter = 0; michael@0: michael@0: function worker(me) { michael@0: let him = 1 - me; michael@0: michael@0: for (let i = 0; i < N; i++) { michael@0: // enter the mutex michael@0: f[me] = true; michael@0: while (f[him]) { michael@0: if (turn != me) { michael@0: f[me] = false; michael@0: while (turn != me) michael@0: ; // busy wait michael@0: f[me] = true; michael@0: } michael@0: } michael@0: michael@0: // critical section michael@0: let x = counter; michael@0: sleep(0.003); michael@0: counter = x + 1; michael@0: michael@0: // leave the mutex michael@0: turn = him; michael@0: f[me] = false; michael@0: } michael@0: michael@0: return 'ok'; michael@0: } michael@0: michael@0: var expect; michael@0: var actual; michael@0: michael@0: if (typeof scatter == 'undefined' || typeof sleep == 'undefined') { michael@0: print('Test skipped. scatter or sleep not defined.'); michael@0: expect = actual = 'Test skipped.'; michael@0: } else { michael@0: var results = scatter([function () { return worker(0); }, michael@0: function () { return worker(1); }]); michael@0: michael@0: expect = "Thread status: [ok,ok], counter: " + (2 * N); michael@0: actual = "Thread status: [" + results + "], counter: " + counter; michael@0: } michael@0: michael@0: reportCompare(expect, actual, summary);