GM_lock

A lightweight, dependency-free mutex for Userscripts that ensures **only one tab / context** runs a critical section at a time. It coordinates through `GM.setValue` + `GM_addValueChangeListener`, so it works across multiple tabs, iframes, and even separate scripts that share the same @name/@namespace storage.

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.gf.qytechs.cn/scripts/554436/1687660/GM_lock.js

作者
𝖢𝖸 𝖥𝗎𝗇𝗀
版本
0.0.1.20251101184408
建立日期
2025-11-01
更新日期
2025-11-01
尺寸
4.2 KB
授權條款
未知

GM_lock — a tiny cross-tab async lock for userscripts

A lightweight, dependency-free mutex for Userscripts that ensures only one tab / context runs a critical section at a time. It coordinates through GM.setValue + GM_addValueChangeListener, so it works across multiple tabs, iframes, and even separate scripts that share the same @name/@namespace storage.


Why?

Userscripts often run in several places at once (multiple tabs, iframes, reruns). If you have code that must not run concurrently (e.g., rate-limited API calls, queue processing, cache writes), GM_lock(tag, fn) makes that section execute exclusively.


Install

Just copy the function into your script (or @require it, if you publish as a library).
Requires a manager that supports:

  • GM.setValue, GM.listValues, GM.deleteValue
  • GM_addValueChangeListener, GM_removeValueChangeListener

Tested with Tampermonkey, Violentmonkey and ScriptCat. (Greasemonkey 4+ may require adapting API names.)


API

// JavaScript
var GM_lock: <T>(tag: string, func: () => Promise<T> | T) => Promise<T>;
  • tag: A string identifying the lock scope. Same tag ⇒ same lock.
  • func: Your critical section (sync or async).
  • returns: Resolves/rejects with func’s result/error.

Usage

Basic

// Only one instance across all tabs will enter this block at a time
await GM_lock('sync-cache', async () => {
  const data = await fetch('https://api.example.com/data').then(r => r.json());
  await GM.setValue('cache:data', data);
});

How it works

  • Each contender writes a key: GM_lock::<tag>::<lockId>.

    • lockId = TS_i_R, where:
    • TS: a 16-digit positive integer representing Date.now() offset (prefixed large timestamp),
    • i: a process-local counter (GM_lock.i rolls under 2^30),
    • R: a 4-digit random.
  • Everyone listens on GM_lock_changed::<tag> via GM_addValueChangeListener.

  • The lexicographically smallest GM_lock::<tag>::… key wins the election and runs func.

  • Notifications:

    • _set_ — contender (re)announces presence
    • _run_ — winner starts critical section
    • _del_ — winner deletes its lock key when done
  • Small delays (~50 ms) reduce race windows during elections.

  • Recovery / cleanup: A two-step timer helps progress if events are missed or records are stale:

    • ~300 ms after entry, the contender re-sets its key and emits _set_.
    • After a further ~300 ms (~600 ms total), it removes older/invalid GM_lock::<tag>::… keys that weren’t recently seen, then re-emits _set_.
    • This handles crashed tabs and stale keys without busy-waiting.

This design is event-driven, cross-context, and minimizes polling.


Notes & Tips

  • Use short, stable tags. Different features ⇒ different tags.
  • Your func may throw/reject; that error bubbles out of GM_lock.
  • Don’t block the event loop inside func for long periods; prefer awaiting async work.
  • If a tab dies mid-lock, the ~600 ms recovery pass helps other contenders move forward.
  • Fairness is best-effort (driven by key sort order) and not strictly FIFO under heavy contention.

License

This project uses the Unlicense.

  This is free and unencumbered software released into the public domain.

  Anyone is free to copy, modify, publish, use, compile, sell, or
  distribute this software, either in source code form or as a compiled
  binary, for any purpose, commercial or non-commercial, and by any
  means.

  In jurisdictions that recognize copyright laws, the author or authors
  of this software dedicate any and all copyright interest in the
  software to the public domain. We make this dedication for the benefit
  of the public at large and to the detriment of our heirs and
  successors. We intend this dedication to be an overt act of
  relinquishment in perpetuity of all present and future rights to this
  software under copyright law.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.

  For more information, please refer to <https://unlicense.org>

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址