{"id":31051547,"url":"https://github.com/paperstrike/async-shared-mutex","last_synced_at":"2026-01-20T17:03:22.592Z","repository":{"id":312571985,"uuid":"1047846289","full_name":"PaperStrike/async-shared-mutex","owner":"PaperStrike","description":null,"archived":false,"fork":false,"pushed_at":"2025-09-10T16:01:30.000Z","size":43,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-09-10T20:08:16.519Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/PaperStrike.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-08-31T11:19:13.000Z","updated_at":"2025-09-10T16:00:56.000Z","dependencies_parsed_at":"2025-08-31T16:45:32.210Z","dependency_job_id":"21ee141e-4211-46a1-9fc3-b59547ab02f7","html_url":"https://github.com/PaperStrike/async-shared-mutex","commit_stats":null,"previous_names":["paperstrike/async-shared-mutex"],"tags_count":6,"template":false,"template_full_name":null,"purl":"pkg:github/PaperStrike/async-shared-mutex","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PaperStrike%2Fasync-shared-mutex","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PaperStrike%2Fasync-shared-mutex/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PaperStrike%2Fasync-shared-mutex/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PaperStrike%2Fasync-shared-mutex/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PaperStrike","download_url":"https://codeload.github.com/PaperStrike/async-shared-mutex/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PaperStrike%2Fasync-shared-mutex/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28607624,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-20T16:10:39.856Z","status":"ssl_error","status_checked_at":"2026-01-20T16:10:39.493Z","response_time":117,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-09-15T00:28:33.827Z","updated_at":"2026-01-20T17:03:22.575Z","avatar_url":"https://github.com/PaperStrike.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# async-shared-mutex\n\n[![npm Package](https://img.shields.io/npm/v/async-shared-mutex?logo=npm \"async-shared-mutex\")](https://www.npmjs.com/package/async-shared-mutex)\n\n\nLightweight shared (reader) / exclusive (writer) mutex for TypeScript / ESM. Two flavors:\n\n* `SharedMutex` – low‑level handle based API (you manage the critical section).\n* `AsyncSharedMutex` – convenience API that runs a function while holding the mutex.\n\nBoth support shared (concurrent) and exclusive (mutually exclusive) acquisition.\n\n## Quick start (task style)\n\n```ts\nimport { AsyncSharedMutex } from 'async-shared-mutex'\n\nconst mtx = new AsyncSharedMutex()\n\n// Exclusive (writer)\nawait mtx.lock(async () =\u003e {\n  // only one task may run here\n  await doWrite()\n})\n\n// Shared (reader) – many may run together\nconst [a, b, c] = await Promise.all([\n  mtx.lockShared(() =\u003e readValue('a')),\n  mtx.lockShared(() =\u003e readValue('b')),\n  mtx.lockShared(() =\u003e readValue('c')),\n])\n```\n\n## Quick start (handle style)\n\n```ts\nimport { SharedMutex } from 'async-shared-mutex'\n\nconst mtx = new SharedMutex()\n\n// Exclusive\nconst exclusive = await mtx.lock()\ntry {\n  await doWrite()\n}\nfinally {\n  exclusive.unlock()\n}\n\n// Shared\nconst shared = await mtx.lockShared()\ntry {\n  const v = await readValue()\n  console.log(v)\n}\nfinally {\n  shared.unlock()\n}\n```\n\n### With TypeScript `using` (TS 5.2+)\n\n```ts\nimport { SharedMutex } from 'async-shared-mutex'\nconst mtx = new SharedMutex()\n\nasync function doStuff() {\n  using lock = await mtx.lock() // unlocks automatically at end of scope\n  await mutate()\n}\n```\n\n\u003e If your runtime lacks native `Symbol.dispose`, add a small polyfill (see `test/helpers/patchDisposable.ts` for an example) or keep calling `unlock()` manually.\n\n## When to use\n\nUse for coordinating access to a resource where:\n\n* Multiple readers may safely proceed concurrently.\n* Writers need full exclusivity (no readers or other writers).\n* Writers should not starve behind an ever‑arriving stream of readers.\n\n## Semantics\n\n* Shared acquisitions overlap with other shared acquisitions provided no earlier exclusive is pending / active.\n* An exclusive waits for all currently active (or already queued *before it*) shared holders to finish, then runs alone.\n* Shared acquisitions requested **after** an exclusive has queued must wait until that exclusive finishes.\n* Exclusives are serialized in request order.\n* Errors inside a task (or your critical section) propagate; the mutex is still unlocked.\n* `try*` variants attempt an instantaneous acquisition; they return `null` if not immediately possible (no waiting side effects).\n\nThis gives predictable writer progress (no writer starvation) while still batching readers that arrive before the next writer.\n\n## API\n\n### `class SharedMutex`\n\nLow level; you get locks you must unlock.\n\n| Method | Returns | Description |\n| ------ | ------- | ----------- |\n| `lock()` | `Promise\u003cLockHandle\u003e` | Await for an exclusive (writer) handle. |\n| `tryLock()` | `LockHandle \\| null` | Immediate exclusive attempt. `null` if busy. |\n| `lockShared()` | `Promise\u003cLockHandle\u003e` | Await for a shared (reader) handle. |\n| `tryLockShared()` | `LockHandle \\| null` | Immediate shared attempt (fails if an exclusive is active/pending). |\n\n`LockHandle`:\n\n* `unlock(): void` – idempotent; may be called multiple times.\n* `[Symbol.dispose]()` – same as `unlock()` enabling `using`.\n\n### `class AsyncSharedMutex`\n\nWraps `SharedMutex` and runs a function while holding the mutex.\n\n| Method | Returns | Description |\n| ------ | ------- | ----------- |\n| `lock(task)` | `Promise\u003cT\u003e` | Run `task` exclusively. |\n| `tryLock(task)` | `Promise\u003cT\u003e \\| null` | Immediate exclusive attempt. If acquired, runs `task`; else `null`. |\n| `lockShared(task)` | `Promise\u003cT\u003e` | Run `task` under a shared lock. |\n| `tryLockShared(task)` | `Promise\u003cT\u003e \\| null` | Immediate shared attempt. |\n\n`task` signature: `() =\u003e T | PromiseLike\u003cT\u003e`\n\n### Error handling\n\nIf `task` throws / rejects, the mutex is unlocked and the error is re-thrown. No additional wrapping.\n\n### Ordering example\n\n```txt\ntime →\nS S S (queued)    E (queued after those S)  S S (queued after E)\n|\u003c--- overlap ---\u003e|\u003c--- exclusive alone ---\u003e|\u003c--- overlap ---\u003e|\n```\n\n## Patterns\n\nDebounce writes while permitting many simultaneous reads:\n\n```ts\nconst stateMtx = new AsyncSharedMutex()\nlet state: Data\n\nexport const readState = () =\u003e stateMtx.lockShared(() =\u003e state)\nexport const updateState = (patch: Partial\u003cData\u003e) =\u003e stateMtx.lock(async () =\u003e {\n  state = { ...state, ...patch }\n})\n```\n\nAttempt a fast read path that falls back to waiting if a writer is in flight:\n\n```ts\nconst mtx = new SharedMutex()\n\nexport async function getSnapshot(): Promise\u003cSnapshot\u003e {\n  const h = mtx.tryLockShared() || await mtx.lockShared()\n  try {\n    return snapshot()\n  }\n  finally {\n    h.unlock()\n  }\n}\n```\n\n## Target\n\nModern Node / browsers, ES2022.\n\n## Limitations / Notes\n\n* Not reentrant – calling lock methods from inside an already held lock will deadlock your logic (no detection performed).\n* Fairness beyond the described ordering is not attempted (e.g. readers arriving while a long queue of writers exists will wait until those writers finish).\n* No timeout / cancellation primitive provided. Compose with `AbortController` in your tasks if required.\n\n## Comparison\n\n| | `SharedMutex` | `AsyncSharedMutex` |\n| - | - | - |\n| Style | Manual handles | Higher level task runner |\n| Cleanup | Call `unlock()` / `using` | Automatic around function |\n| Overhead | Slightly lower | Wrapper promise per task |\n\n## License\n\nMIT\n\n---\n\nFeel free to open issues / PRs for ideas (timeouts, cancellation helpers, metrics, etc.).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpaperstrike%2Fasync-shared-mutex","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpaperstrike%2Fasync-shared-mutex","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpaperstrike%2Fasync-shared-mutex/lists"}