Greasy Fork is available in English.
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.
此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.greasyfork.icu/scripts/554436/1687660/GM_lock.js
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.
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.
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.deleteValueGM_addValueChangeListener, GM_removeValueChangeListenerTested with Tampermonkey, Violentmonkey and ScriptCat. (Greasemonkey 4+ may require adapting API names.)
// JavaScript
var GM_lock: <T>(tag: string, func: () => Promise<T> | T) => Promise<T>;
func’s result/error.// 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);
});
Each contender writes a key: GM_lock::<tag>::<lockId>.
lockId = TS_i_R, where:Date.now() offset (prefixed large timestamp),GM_lock.i rolls under 2^30),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 doneSmall delays (~50 ms) reduce race windows during elections.
Recovery / cleanup: A two-step timer helps progress if events are missed or records are stale:
_set_.GM_lock::<tag>::… keys that weren’t recently seen, then re-emits _set_.This design is event-driven, cross-context, and minimizes polling.
func may throw/reject; that error bubbles out of GM_lock.func for long periods; prefer awaiting async work.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>