futoin-asyncsteps
Version:
Mimic traditional threads in single threaded event loop
145 lines (142 loc) • 6.73 kB
JavaScript
;
/**
* @file
* @author Andrey Galkin <andrey@futoin.org>
*
*
* Copyright 2014-2017 FutoIn Project (https://futoin.org)
* Copyright 2014-2017 Andrey Galkin <andrey@futoin.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var ISync = require('./ISync');
var _require = require('./Errors'),
DefenseRejected = _require.DefenseRejected;
var mtx_sync = function mtx_sync(asp, mtx, step, on_error) {
var root = asp._root;
var release_step = function release_step(asi) {
mtx._release(root);
root._handle_success(asi._call_args);
};
asp._on_cancel = mtx._release_handler;
asp._queue = [[function (asi) {
if (mtx._lock(asp, root)) {
root._handle_success(asp._call_args);
} else {
asi.waitExternal();
asi._call_args = asp._call_args;
}
}, undefined], [step, on_error], [release_step, undefined]];
};
/**
* Mutual exclusion mechanism for AsyncSteps
*/
var Mutex = /*#__PURE__*/function (_ISync) {
/**
* C-tor
* @param {number} [max] - maximum number of simultaneous critical section entries
* @param {?number} [max_queue] - limit queue length, if set
*/
function Mutex() {
var _this;
var max = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
var max_queue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
_classCallCheck(this, Mutex);
_this = _callSuper(this, Mutex);
_this._max = max;
_this._locked = 0;
_this._owners = new WeakMap();
_this._queue = [];
_this._max_queue = max_queue;
_this._release_handler = function (asi) {
_this._release(asi._root);
};
return _this;
}
_inherits(Mutex, _ISync);
return _createClass(Mutex, [{
key: "_lock",
value: function _lock(asi, root) {
var owners = this._owners;
var owned = owners.get(root);
if (owned) {
owners.set(root, owned + 1);
return true;
} else if (this._locked >= this._max) {
var queue = this._queue;
var max_queue = this._max_queue;
if (max_queue !== null && queue.length >= max_queue) {
root.error(DefenseRejected, 'Mutex queue limit');
}
queue.push(asi);
return false;
} else {
this._locked += 1;
owners.set(root, 1);
return true;
}
}
}, {
key: "_release",
value: function _release(root) {
var owners = this._owners;
var owned = owners.get(root);
if (owned) {
if (owned > 1) {
owners.set(root, owned - 1);
return;
}
owners["delete"](root);
this._locked -= 1;
var queue = this._queue;
while (queue.length) {
var other_as = queue.shift();
if (other_as.state) {
var other_root = other_as._root;
this._lock(other_as, other_root);
other_root._handle_success(other_as._call_args);
break;
}
}
} else {
var idx = this._queue.indexOf(root);
if (idx >= 0) {
this._queue.splice(idx, 1);
}
}
}
}, {
key: "sync",
value: function sync(as, step, onerror) {
var _this2 = this;
as.add(function (as) {
mtx_sync(as, _this2, step, onerror);
});
}
}]);
}(ISync);
module.exports = Mutex;
//# sourceMappingURL=Mutex.js.map