mutex-ts
Version:
This package provides two classes for managing locks: `Mutex` and `MutexRW`. These locks can be used to control access to critical sections in a multi-threaded or asynchronous environment.
2 lines (1 loc) • 1.54 kB
JavaScript
(function(e,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(e=typeof globalThis<"u"?globalThis:e||self,s(e.index={}))})(this,function(e){"use strict";var c=Object.defineProperty;var h=(e,s,o)=>s in e?c(e,s,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[s]=o;var r=(e,s,o)=>(h(e,typeof s!="symbol"?s+"":s,o),o);function s(){}class o{constructor(){r(this,"m_lastPromise",Promise.resolve())}async obtain(t=!1){let i=s;if(t)return i;const n=this.m_lastPromise;return this.m_lastPromise=new Promise(a=>i=a),await n,i}async lock(t=!1){return{[Symbol.dispose]:await this.obtain(t)}}}class m{constructor(){r(this,"m_nextRWPromise",Promise.resolve());r(this,"m_lastRWPromise",Promise.resolve());r(this,"m_lastROPromise",Promise.resolve());r(this,"roAccessCnt",0);r(this,"rwAccess",!1)}async obtainRO(){for(;this.rwAccess;)await this.m_lastRWPromise;++this.roAccessCnt;let t=s;const i=new Promise(n=>t=n);return this.m_lastROPromise=Promise.all([i,this.m_lastROPromise]),i.then(()=>--this.roAccessCnt),t}async lockRO(){return{[Symbol.dispose]:await this.obtainRO()}}async obtainRW(){let t=s;const i=this.m_nextRWPromise,n=new Promise(a=>t=a);for(this.m_nextRWPromise=n,await i;this.roAccessCnt;)await this.m_lastROPromise;return this.rwAccess=!0,this.m_lastRWPromise=n,this.m_lastRWPromise.then(()=>this.rwAccess=!1),t}async lockRW(){return{[Symbol.dispose]:await this.obtainRW()}}}e.Mutex=o,e.MutexRW=m,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});