Public
Back
Version 23
8/22/2023
let safeCounter = async () => {
// 1. Try to acquire a lock
let { lease } = await stevekrouse.dlock();
console.log(lease);
if (!lease) {
// 2. wait a second and try to acquire it again
await stevekrouse.sleep(1000);
return me.safeCounter();
}
// 3. I have a lock!
// 4. Get most up to date state
//
// Note 1: If I referenced @stevekrouse.threadsafeStateEx here
// it would return the value of that val at the beginning of this function,
// before I acquired the lock. I fetch it's value now to get the most up-to-date
// value of it, now that I know it can't be updated until I release this lock.
//
// Note 2: I use `@stevekrouse.runValAPI` here instead of `api` (used below)
// because `api` only works on funcitons and @stevekrouse.threadsafeStateEx
// is a JSON val.
let { state } = await stevekrouse.runValAPI(
"@stevekrouse.threadsafeStateEx",
);
// 5. Update the state
//
// Note 3: I update the state via an API call here to ensure that the state
// is fully updated *before* I release the lock. If I were to update the state
// directly in this val, `@stevekrouse.updateThreadsafeStateEx = `, those
// changes wouldn't be saved in the database until *after* I released the lock
let newState = state + 1;
await api(stevekrouse.updateThreadsafeStateEx, {
lease,
state: newState,
});
// 6. i release the lock
await stevekrouse.dlock({ release: true });
Updated: October 23, 2023